Jest: fake setInterval not working as expected

Created on 23 Nov 2017  路  1Comment  路  Source: facebook/jest

First of all, thank you so much for creating this AMAZING tool! It's really inspiring in terms of developer experience.

What is the current behavior?
runAllTimers() results in a setInterval mock with only 1 call.

If the current behavior is a bug, please provide the steps to reproduce and
馃憞 Open in project

/* Test */
it.only('should update the reamining time every second', () => {
  const timeInMinutes = 0.1
  const wrapper = shallow(<Timer time={timeInMinutes} />)

  wrapper.find('.start').simulate('click')   
  jest.runAllTimers()

  expect(setInterval.mock.calls.length).toBe(5) // Received: 1
})

馃憞 Open in project

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

What is the expected behavior?
Unless I misunderstood the docs, setInterval should have ran until it met the condition where the interval is cleared.

Please provide your exact Jest configuration and mention your Jest, node,
yarn/npm version and operating system.

{
   jest: 20.0.4 // latest, unless I eject CRA
   node: v6.10.2
   yarn: 1.1.0
   osx: Sierra 10.12.6
}

Most helpful comment

wrong forum... you are also using the wrong function. Use jest.runOnlyPendingTimers():

>All comments

wrong forum... you are also using the wrong function. Use jest.runOnlyPendingTimers():

Was this page helpful?
0 / 5 - 0 ratings