0
子供がタイマーを開始できるようにするTimerコンポーネントを作成しようとしていて、1秒間隔でどれだけの時間が残っているかを示します。Jest:偽のsetIntervalが期待通りに動作しない
/* 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 })
}
私は次のテストを持っています
コードは機能します。問題は、テストでは、setInteval.mock.calls.length = 1
ですが、問題ではありません。
Jest fake timerについて誤解されていることはありますか?
ありがとうございました❤️