最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unit test method that calls clearInterval with Jest and Enzyme on React - Stack Overflow

programmeradmin2浏览0评论

I have this React ponent and it have method that calls clearInterval to clear the interval set by other method

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

I have this React ponent and it have method that calls clearInterval to clear the interval set by other method

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

How do i test those method?

edited: add test i did

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

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

I've been googling for days, tried using jest.useFakeTimers() and call expect(clearInterval).toHaveBeenCalledWith(expect.any(Function), 1000) and a lot of other absurd way to test this method that i forgot, all to no avail.

So ... if anybody have a solution and kind enough to share here, i could pass this weekend with a happy smiling face and a heart full of joy.

Thanks in advance. Cheers!

Share Improve this question edited Nov 8, 2018 at 10:05 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Jul 6, 2018 at 4:42 sirnobrainsirnobrain 1331 silver badge8 bronze badges 3
  • clearInterval only takes the interval identifier as an argument. Try expect(clearInterval).toHaveBeenCalledWith(expect.any(Function)). Can you post your test file? – Derek Commented Jul 6, 2018 at 4:57
  • i added the test i did – sirnobrain Commented Jul 6, 2018 at 6:39
  • Not sure if this is the actual code but claerIntervalMethod is misspelled in SomeComponent. – Alan Friedman Commented Jul 7, 2018 at 23:35
Add a ment  | 

1 Answer 1

Reset to default 6

setInterval returns a number, not a function. Try:

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

Also, as mentioned in my ment, is misspelled in your example (not sure if actual code).

发布评论

评论列表(0)

  1. 暂无评论