fakeAsync 不适用于 debounceTime

fakeAsync does not work with debounceTime

我正在尝试使用 debounceTime (rxjs) 为 Angular 应用中的功能编写单元测试。并使用 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

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(); ... }