测试反应,sinon或开玩笑的计时器

时间:2018-05-31 06:53:33

标签: reactjs unit-testing timer jestjs sinon

我有一个功能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
})

收到错误:

  

预期模拟函数被调用一次,但它被称为零次。

我试图遵循这些例子

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)
  

无法阅读财产&#39;来电&#39;未定义的

expect(setInterval).toHaveBeenCalledTimes(1)
  

值必须是模拟函数或间谍。

1 个答案:

答案 0 :(得分:0)

原来间谍应该声明为:

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