使用 sinon 测试绑定事件函数

test bind event function with sinon

我无法找到 sinon 间谍未被触发的原因。

其实很开心:
1.控制台打印touchStartHandler
2. touchstartSpy.callCount 是 0

我用了 TypeScript React jest enzyme sinon

这是我的一项测试的大致情况: *.ts:

constructior (props: ICompatibleDivProps) {
  super(props)
  this.touchStartHandler = this.touchStartHandler.bind(this)
}

componentDidMount () {
  this.divElement.addEventlistener('touchstart', this.touchStartHandler, { passive: true })  
}

render () {
  const { style, className} = this.props
  retutn (
    <div>
      ref={div => this.divElement = div}
      style={style}
      className={className}
      onClick={this.props.onClick}
    </div>
  )
}

touchStartHandler (e: TouchEvent) {
  console.log('touchStartHandler')
}

*.test.ts:

mport { mount } from 'enzyme'
import CompatibleDiv from './CompatibleDiv'
import { spy } from 'sinon'
test('event called is normal', () => {
  const wrapper = mount(
    <CompatibleDiv />
  )
  const instance = wrapper.instance() as CompatibleDiv
  const touchstartSpy = spy(CompatibleDiv.prototype, 'touchStartHandler')

  const div = wrapper.find('div').getDOMNode()
  div.dispatchEvent(new Event('touchstart'))

  expect(touchstartSpy.callCount).toBe(1)
})

我在这里错过了什么?

谢谢!

你应该直接监视 CompatibleDiv 组件而不是它的实例,所以...

const touchstartSpy = spy(CompatibleDiv.prototype, 'touchStartHandler')

...你想在渲染组件之前这样做,所以在文件的顶部,在 test.

之前