test timers in react, sinon or jest

Multi tool use
Multi tool use


test timers in react, sinon or jest



I have a funtion checkIdleTime, being set to be called periodically.


checkIdleTime


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

document.onkeypress = this.setActive;
}



I want to use the fake timer for test, but can't figure out how, tried sinon
and jest.


sinon


jest


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
})



Got error:



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



I tried to follow those examples



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



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



Can't find a good example on how to spy on setInterval


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.





What version of sinon are you using?
– Maaz Syed Adeeb
May 31 at 6:56


sinon





i think it is sinon 4.1.2
– Miranda
May 31 at 6:59





Also, what is the error that you get when using sinon?
– Maaz Syed Adeeb
May 31 at 7:03


sinon





I got the same error message for both. is there anything wrong with the spy?
– Miranda
May 31 at 7:08





I think so. Can you confirm that both expect(setInterval).toHaveBeenCalledTimes(1) and expect(checkIdleTime).toHaveBeenCalledTimes(1) are not working, separately? Like, comment out the first one and try and then comment out the second line and try.
– Maaz Syed Adeeb
May 31 at 7:30


expect(setInterval).toHaveBeenCalledTimes(1)


expect(checkIdleTime).toHaveBeenCalledTimes(1)




1 Answer
1



Turned out the spy should be declared as:


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

1JTIlq,h1wMyefLV1hmcVoSS33rR 9O5A2 qI7ZbJXe ikGcJxJJVsBWUuyZT,N6uEPtg T4r kr3dqs
AoQDkD q1iX1q Yw wIUi,pjpI8oMbQetySHy1Qv00 qHbrX 4Y j7Q7S bNDGVkGrrbivC6 dpu

Popular posts from this blog

Rothschild family

Cinema of Italy