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

sir*_*ain 3 javascript testing reactjs jestjs enzyme

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

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

我该如何测试那些方法?

编辑:添加我做过的测试

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

  jest.useFakeTimers()
  clearIntervalMethod()
  expect(clearInterval).toHaveBeenCalledWith(expect.any(Function))
})
Run Code Online (Sandbox Code Playgroud)

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

因此,...如果有人能在这里分享解决方案,并且愿意在这里分享我的心意,那么我可以度过愉快的笑容和充满喜悦的心情度过这个周末。

提前致谢。干杯!

Ala*_*man 5

setInterval 返回一个数字,而不是一个函数。尝试:

expect(clearInterval).toHaveBeenCalledWith(expect.any(Number))
Run Code Online (Sandbox Code Playgroud)

另外,如我的评论中所述,在您的示例中拼写错误(不确定实际代码是否正确)。