I'm trying to create a Timer component, that allows children to start a timer, and then provides them with how much time is left in 1 second intervals.
I have the following test:
/* Test */
jest.useFakeTimers()
it.only('should update the reamining time every second', () => {
const time = 1/12
const wrapper = shallow(<Timer time={time} />)
wrapper.find('.start').simulate('click')
jest.runAllTimers()
expect(setInterval.mock.calls.length).toBe(4)
})
/* Code */
updateTimeLeft() {
const now: number = +new Date()
const timeLeft = this.state.endTime - now
if (timeLeft < 0) {
clearInterval(this.state.timeInterval)
}
this.setState({ timeLeft })
}
intializeTimer(minutes: number) {
const startTime: number = new Date().getTime()
const endTime: number = new Date(startTime + minutes * 60 * 1000).getTime()
this.setState({
startTime,
endTime
})
const timeInterval: NodeJS.Timer = global.setInterval(
() => this.updateTimeLeft(),
1000
)
this.setState({ timeInterval })
}
The code works. The problem is, in the test, setInteval.mock.calls.length = 1, not matter what.
Is there anything I misunderstood about Jest fake timers?
Thank you ❤️