用sinon测试绑定事件函数

时间:2018-03-28 10:50:22

标签: sinon enzyme

我无法追查为什么没有触发一个罪人间谍。

实际上很开心:
  1.控制台打印touchStartHandler
  2. touchstartSpy.callCount为0

我使用 TypeScript React jest酶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)
})

我在这里缺少什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

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