我正在尝试使用Angular
(debounceTime
)在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
答案 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');
...
}));
})
_complete(){ this.debouncedNext(); ... }