繁体   English   中英

为什么jest.useFakeTimers不能使用RxJs Observable延迟

[英]Why is jest.useFakeTimers not working with RxJs Observable delay

我想知道为什么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作为jest.runTimersToTime的参数没有任何区别。 使用jest.runAllTimers()使测试过去

delay运算符不适用于Jest的假定时器,因为delay运算符的实现使用了调度程序的时间概念 - 这与Jest的假时间概念无关。

来源在这里

while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
  queue.shift().notification.observe(destination);
}

当前(非假)时间在创建时分配给通知,当前时间是调度程序now方法返回的时间。 当使用Jest的假定时器时,实际(非假)时间量将不足,通知将保留在队列中。

要使用假或虚拟时间编写RxJS测试,可以使用VirtualTimeScheduler 看到这个答案 或者您可以使用TestScheduler大理石测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM