2017-11-22 5 views
0

子供がタイマーを開始できるようにするTimerコンポーネントを作成しようとしていて、1秒間隔でどれだけの時間が残っているかを示します。Jest:偽のsetIntervalが期待通りに動作しない

Full Code

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

Full Code

/* 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について誤解されていることはありますか?

ありがとうございました❤️

答えて

1

偽のタイマーは何もありません。 initializeTimer内でsetIntervalを1回呼び出すだけです。そのため、setInterval.mock.calls.lengthには1が表示されます。しかし、コールバック関数は必要なだけ呼び出されます。 forループと考えると、ループ宣言(ここではsetInterval)と必要なボディコール(ここのコールバック関数)が1つだけです。

希望します。

関連する問題