在 react、sinon 或 jest 中测试计时器

test timers in react, sinon or jest

我有一个函数 checkIdleTime,设置为定期调用。

componentDidMount() {
    var idleCheck = setInterval(this.checkIdleTime.bind(this), authTimeoutSeconds * 1000);
    this.setState({idleCheck: idleCheck});

    document.onkeypress = this.setActive;
}

我想用假计时器做测试,但不知道怎么用,试过了sinonjest.

beforeEach(() => {   
    checkIdleTime = jest.spyOn(PureMain.prototype, 'checkIdleTime');
    wrapper = shallow(
        <PureMain/>
    );

    jest.useFakeTimers();
    //clock = sinon.useFakeTimers();  
});

it('should check the idle time after [authTimeoutSeconds] seconds of inactivity', () => {

    wrapper.instance().componentDidMount();

    var idleCheck_timeout = wrapper.instance().state.idleCheck;
    expect(idleCheck_timeout).not.toEqual(null);
    expect(idleCheck_timeout._idleTimeout).toBe(authTimeoutSeconds * 1000);
    jest.runAllTimers();
    //clock.tick(authTimeoutSeconds * 1000 * 2);
    expect(setInterval).toHaveBeenCalledTimes(1);//not work
    expect(checkIdleTime).toHaveBeenCalledTimes(1);//not work
})

出现错误:

Expected mock function to have been called one time, but it was called zero times.

我尝试遵循这些示例

https://facebook.github.io/jest/docs/en/timer-mocks.html

http://sinonjs.org/releases/v1.17.7/fake-timers/


找不到关于如何监视 setInterval

的好例子
expect(setInterval.mock.calls.length).toBe(1)

Cannot read property 'calls' of undefined

expect(setInterval).toHaveBeenCalledTimes(1)

value must be a mock function or spy.

原来间谍应该声明为:

setTimeout_spy = jest.spyOn(window, 'setTimeout');