fakeAsync不适用于debounceTime

时间:2019-10-07 15:48:11

标签: angular rxjs jasmine debounce

我正在尝试使用AngulardebounceTime)在rxjs应用中编写功能的单元测试。并使用fakeAsync进行异步测试。 而且看起来在测试debounceTime中,即使我没有设置tick()或像tick(500)这样的小间隔对其进行设置,它也会立即得到解决。

例如使用delay(1000)代替debounceTime(1000) fakeAsync可以很好地工作。

测试

describe('rr', () => {
    it('should get Date diff correctly in fakeAsync with rxjs scheduler', fakeAsync(() => {
        let result = null;
        of ('hello').pipe(debounceTime(1000)).subscribe(v => { result = v; });
        expect(result).toBeNull(); // But it is 'Hello' - debounceTime resolves immediately
        tick(1000);
        expect(result).toBe('hello');
...
  }));
})

stackblitz https://stackblitz.com/edit/angular-ohhi9e?file=src%2Fapp%2Fapp.component.spec.ts

1 个答案:

答案 0 :(得分:2)

of运算符在收到通知后立即完成。如果不需要其他通知,则debounceTime无需等待,因此可以在发出完整通知时立即进行通知。

要获得结果,请尝试使用Subject之类的长寿命可观察物。

describe('rr', () => {
    it('should get Date diff correctly in fakeAsync with rxjs scheduler', fakeAsync(() => {
        let result = null;
        new BehaviourSubject ('hello').pipe(debounceTime(1000)).subscribe(v => { result = v; });
        expect(result).toBeNull();
        tick(1000);
        expect(result).toBe('hello');
...
  }));
})

来源:debounceTime on GitHub

  

_complete(){       this.debouncedNext();   ...     }