【问题标题】:Writing test to make sure function is called from subscribe block编写测试以确保从订阅块调用函数
【发布时间】:2021-06-11 19:04:40
【问题描述】:

我正在尝试为 MyComponent 中的以下订阅块编写测试

ngOnInit() {
// Initalize listener for year dropdown change
    this.yearChangeSubscription = this.searchForm.get('year')?.valueChanges.pipe(
      debounceTime(400),
      distinctUntilChanged(),
      switchMap((year: string) => {
        return of(year);
      })
    ).subscribe((year: string) => {
      console.log('yearChange');
      this.filterData({ year });
    });
}

我想确保在更改年份表单控件中的值时调用 filterData 函数。所以我写了以下规范。

fit('should call filterData', fakeAsync(() => {
    component.searchForm.controls.year.setValue('2005');
    fixture.detectChanges();
    flush();
    const spy: any = jasmine.createSpyObj('MyComponent', ['filterData']);
    expect(component.searchForm.controls.year.value).toEqual('2005');
    expect(spy.filterData).toHaveBeenCalledTimes(1);
  }));

第一个期望通过了,但第二个期望失败了。 我可以在终端上看到yearChange 控制台日志。

知道我在这里做错了什么吗?

【问题讨论】:

    标签: angular unit-testing rxjs jasmine


    【解决方案1】:

    可能是debounceTime 没有被等待。

    试试这个:

    fit('should call filterData', fakeAsync(() => {
        const filterSpy = spyOn(component, 'filterData');
        component.searchForm.controls.year.setValue('2005');
        // make 401ms pass in a fake way
        tick(401);
        expect(component.searchForm.controls.year.value).toEqual('2005');
        expect(filterSpy).toHaveBeenCalledTimes(1);
      }));
    

    【讨论】:

    • 还是不行。我已经添加了 flush() 应该已经处理了等待。
    • 我不确定,抱歉。如果您看到yearChangelog,那么我认为测试应该通过了。
    猜你喜欢
    • 2020-08-31
    • 2020-11-03
    • 2018-12-15
    • 2022-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多