I'm wondering why jest.useFakeTimers
is working with setTimeout
but not with the delay operator of 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);
});
});
FYI: using 20 or 2000 as an argument for jest.runTimersToTime
makes no difference.
Using jest.runAllTimers()
makes the test past
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…