我想知道为什么jest.useFakeTimers
使用setTimeout
但不使用 RxJs 的延迟运算符:
jest.useFakeTimers();
import {Observable} from 'rxjs/Observable';
import 'rxjs';
describe('timers', () => {
it('should resolve setTimeout synchronously', () => {
const spy = jest.fn();
setTimeout(spy, 20);
expect(spy).not.toHaveBeenCalled();
jest.runTimersToTime(20);
expect(spy).toHaveBeenCalledTimes(1);
});
it('should resolve setInterval synchronously', () => {
const spy = jest.fn();
setInterval(spy, 20);
expect(spy).not.toHaveBeenCalled();
jest.runTimersToTime(20);
expect(spy).toHaveBeenCalledTimes(1);
jest.runTimersToTime(20);
expect(spy).toHaveBeenCalledTimes(2);
});
it('should work with observables', () => {
const delay$ = Observable.of(true).delay(20);
const spy = jest.fn();
delay$.subscribe(spy);
expect(spy).not.toHaveBeenCalled();
jest.runTimersToTime(2000);
expect(spy).toHaveBeenCalledTimes(1);
});
});
仅供参考:使用 20 或 2000 作为参数 forjest.runTimersToTime
没有区别。使用jest.runAllTimers()
使测试过去