【问题标题】:test timers in react, sinon or jest在 react、sinon 或 jest 中测试计时器
【发布时间】:2018-05-31 06:53:33
【问题描述】:

我有一个函数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)

无法读取未定义的属性“调用”

expect(setInterval).toHaveBeenCalledTimes(1)

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

【问题讨论】:

  • 你使用的是什么版本的sinon
  • 我认为是sinon 4.1.2
  • 另外,您在使用sinon时遇到什么错误?
  • 我收到了同样的错误信息。间谍有什么问题吗?
  • 我想是的。您能否确认expect(setInterval).toHaveBeenCalledTimes(1)expect(checkIdleTime).toHaveBeenCalledTimes(1) 分别不起作用?比如,注释掉第一行并尝试,然后注释掉第二行并尝试。

标签: reactjs unit-testing timer jestjs sinon


【解决方案1】:

原来间谍应该被声明为:

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

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多