1

私のコンポーネントのSubject変更をテストしようとしていますが、カバレッジは決してサブスクライブ機能に入りません。角ユニットテスト観測可能/カルマの対象

タイトルバー-search.component.ts

export class TitlebarSearch implements OnInit { 

    @ViewChild('titleSearchInput') titleSearchInputEl: any; 
    @Input() inputValue: string; 
    @Output() searchText = new EventEmitter<string>(); 
    searchChange: Subject<string> = new Subject<string>(); 


    constructor(private renderer: Renderer) { 

    }  

    /** 
    * Waits a time before send the text to search 
    * 
    * @protected 
    * @memberof TitlebarSearch  
    * 
    */ 
    protected prepareSearchInput() { 
     this.searchChange.debounceTime(500).subscribe(value => { 
      this.searchText.emit(value); 
     }); 
    } 

    /** 
    * Send the text to the searchChange Observable 
    * 
    * @param {string} text 
    * @memberof TitlebarSearch 
    */ 
    public doSubmit(text:string){ 
     this.searchChange.next(text);   
    }  

} 

タイトルバー-search.component.spec.ts

describe('Titlebar Search tests',() => { 
    let fixture; 
    let titlebarComponent; 

    beforeEach(async(() => { 
     //Creates a UserService using a mock class 
     TestBed.configureTestingModule({ 
      declarations: [TitlebarSearch], 
      imports: [FormsModule], 
      //CUSTOM_ELEMENTS_SCHEMA to solve html elements issues 
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ], 
      providers: [Renderer] 
     }).compileComponents().then(() => { 
      fixture = TestBed.createComponent(TitlebarSearch);    
      titlebarComponent = fixture.componentInstance 
     }); 

    })); 

    //specs 
    it('should send the text to detect the change', async((done) => {   
     const text = "Changed text"; 
     titlebarComponent.doSubmit(text); 
     fixture.detectChanges(); 
     titlebarComponent.searchChange.subscribe(textRecived => { 
      expect(textRecived).toEqual(text); 
      done(); 
     })  
    }));   
}); 

doSubmit方法は、入力テキストがあったときに呼び出されますかわった。次にprepareSearchInputはサブジェクトへのサブスクリプションを持っていて、デバウンスで次のサブジェクトを取得して同じテキストを出力します。

私はテストの間違いがどこにあるのかわかりませんが、カバレッジはサブスクリプションコードをカバーしません。インターネット上の例は私を助けませんでした。

答えて

0

私は同じ問題を抱えていましたが、このスレッドでは@jonrsharpeの答えが得られました:Unit test Angular 2 service subject

next()が呼び出される前に、テストの前にサブジェクトサブスクリプションを宣言する必要があります。あなたはこのようにそれを並べ替える場合は、それが動作するはずです:

it('should send the text to detect the change', async((done) => {   
    titlebarComponent.searchChange.subscribe(textRecived => { 
     expect(textRecived).toEqual(text); 
     done(); 
    }) 
    const text = "Changed text"; 
    titlebarComponent.doSubmit(text); 
    fixture.detectChanges(); 
}));  

問題は、ジョンによると、被写体がどのリプレイ/バッファの動作を持っていなかったということでした。

関連する問題