如何在 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. 的错误 我不确定这是测试 subject.Can 的正确方法 谁能告诉我如何使用去抖动时间对主题进行单元测试。提前致谢

如果 this.search 发出一个值:

,你的测试就会成功
// Does not contain a value yet!
search = new Subject<string>();

因此永远不会触发包含 debounceTime 的管道。 使用 fakeAsynctick(400) 的其余测试设置以及间谍定义是正确的。

我不太清楚你想要达到什么目的,但在某些时候你必须调用 component.search.next(someValue) 才能使你的测试工作。