簡體   English   中英

如何使用 angular 的 debounceTime 對 Subject 進行單元測試

[英]How to unit test Subject with a debounceTime in angular

我的一個組件具有 RxJs 主題,其去抖動時間如下所示

 search = new Subject<string>();
 ngOnInit() {
   this.columnSearch = this.search
     .pipe(debounceTime(400), distinctUntilChanged())
     .subscribe((value) => {
       const columnName = this.params.filterParams.colDef.field;
       const searchData = {
         [columnName]: value,
       };
       this.filterColumns(searchData, this.params.listType);
     });
 }

我嘗試為上述函數編寫規范,如下所示

 describe('#ngOnInit', () => {
    it('should call the init', fakeAsync(() => {
      spyOn(component, 'filterColumns').and.callThrough();

      component.ngOnInit();
      tick(400);

      expect(component.filterColumns).toHaveBeenCalled();
    }));
  });

這顯示了一個錯誤,如Expected spy filterColumns to have been called. 我不確定這是測試主題的正確方法。誰能告訴我如何使用去抖動時間對主題進行單元測試。 提前致謝

如果this.search發出一個值,您的測試將起作用:

// Does not contain a value yet!
search = new Subject<string>();

因此,永遠不會觸發包含debounceTime的管道。 使用fakeAsynctick(400)以及間諜定義的其余測試設置是正確的。

我並不完全清楚您要實現的目標,但在某些時候您必須調用component.search.next(someValue)以使您的測試工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM