使用setInterval测试React组件方法

时间:2017-05-11 11:08:29

标签: reactjs testing sinon enzyme

我正在使用胶带,酶,jsdom和sinon进行测试。我想测试一下简单的事情,即调用方法后状态发生了变化。

class Countdown extends Component {
      state = {
        count: 0,
        countdownStatus: 'stopped'
      }

      componentDidUpdate = (prevProps, prevState) => {
       if (this.state.countdownStatus !== prevState.countdownStatus) {
         switch (this.state.countdownStatus) {
           case 'started':
             this.startTimer()
             break
          }
        }
      }

     startTimer = () => {
        this.timer = setInterval(() => {
          const newCount = this.state.count - 1
          this.setState({
            count: newCount >= 0 ? newCount : 0
          })
        }, 1000)
      }

      handleSetCountdown = (seconds) => {
        this.setState({
          count: seconds,
          countdownStatus: 'started'
        })
      }

      render () {
        const {count} = this.state
        return (
          <div>
            <Clock totalSeconds={count} />
            <CountdownForm onSetCountdown={this.handleSetCountdown} />
          </div>
        )
      }
    }

    export default Countdown

这不起作用。它说它通过但是我的最后一次测试总是因某种原因而挂起,所有测试通过但它们都不会退出。也许这是因为setInterval虽然我没有测试它。

test('Countdown =>  should set state to 10, (t) => {
  t.plan(1)
  const wrapper = shallow(<Countdown />)
  wrapper.instance().handleSetCountdown(10)
  wrapper.update()
  t.equal(wrapper.state().count, 10)
})

编辑:好的,我把它搞定了。由于setInterval,测试没有结束。我该如何解决这个问题?

编辑2:解决方案非常简单。我刚刚添加了

var clock = sinon.useFakeTimers()

并且所有测试都应该完成。

0 个答案:

没有答案