在React上使用Jest和Enzyme调用clearInterval的单元测试方法

时间:2018-07-06 04:42:24

标签: javascript reactjs testing jestjs enzyme

我有这个React组件,它有调用clearInterval的方法来清除其他方法设置的间隔

class SomeComponent extends React.Component {
  setIntervalMethod = () => {
    this.interval = setInterval(this.method, 1000)
  }
  claerIntervalMethod = () => {
    clearInterval(this.interval)
  }
  
  render = () => null
}

我该如何测试那些方法?

编辑:添加我做过的测试

it('should call clearInterval()', () => {
  const mounted = shallow(<SomeComponent/>)
  const clearIntervalMethod = mounted.instance().clearIntervalMethod

  jest.useFakeTimers()
  clearIntervalMethod()
  expect(clearInterval).toHaveBeenCalledWith(expect.any(Function))
})

我已经搜寻了好几天了,尝试使用jest.useFakeTimers()并调用expect(clearInterval).toHaveBeenCalledWith(expect.any(Function), 1000)以及许多其他荒谬的方法来测试我忘记的这种方法,但无济于事。

所以...如果有人能在这里分享解决方案并友好地在这里分享我的话,我可以带着微笑的笑脸和充满喜悦的心度过这个周末。

先谢谢了。干杯!

1 个答案:

答案 0 :(得分:5)

setInterval returns a number,而不是函数。试试:

expect(clearInterval).toHaveBeenCalledWith(expect.any(Number))

而且,正如我在评论中提到的那样,您的示例中的拼写错误(不确定实际代码是否正确)。