【问题标题】:How do I use sinon on a bound React component method?如何在绑定的 React 组件方法上使用 sinon?
【发布时间】:2017-02-04 00:06:44
【问题描述】:

我在使用带有绑定方法的 Sinon 时遇到了一些困难 (https://babeljs.io/docs/plugins/transform-class-properties/)。

我应该怎么附上间谍?这是一个要点: https://gist.github.com/stevens32/b5eee5cc1781a687be03bf80ce8425e0

结果:

bound method spying
  √ should be an instance of FormComponent
  should spy on boundChangeInput
    √ should have calledOnce prop on boundChangeInput from spy
    1) should have boundChangeInput.calledOnce true on simulated input change
    √ has the correct value
  should spy on notBoundChangeInput
    √ should have calledOnce prop on notBoundChangeInput from spy
    √ should have notBoundChangeInput.calledOnce true on simulated input change
    √ has the correct value

 6 passing (133ms)
  1 failing

  1) bound method spying should spy on boundChangeInput should have boundChangeInput.calledOnce true on
mulated input change:

  AssertionError: expected false to equal true
  + expected - actual

  -false
  +true

【问题讨论】:

  • 没找到方法,选择在组件的构造函数中绑定函数
  • 有人知道为什么有人会否决这个吗?

标签: unit-testing reactjs mocha.js sinon enzyme


【解决方案1】:

您可能需要先创建组件的实例。试试这个:

describe('should have boundChangeInput.calledOnce true on simulated input change', function() {

  const node = mount(<FormComponent />)
  const component = wrapper.instance()

  let boundChangeSpy = sinon.spy(node, 'boundChangeInput')

  component.forceUpdate()
  wrapper.update()

  wrapper.find('input').at(0).simulate('change',{target:{value:'some value'}})

  expect(node.boundChangeSpy.calledOnce).to.equal(true)
})

来源:Test custom method on React component has been called, using Enzyme and Sinon

【讨论】:

  • 谢谢!我尝试使用 wrapper.instance() 但这也没有用 - 看起来 reactInstance.forceUpdate() 和 wrapper.update() 成功了。
  • 这解决了我的问题。我的怀疑是,当您浅渲染组件时,方法绑定发生在组件构造函数中,并且第一个渲染通道使用该版本。毕竟,您在绑定的实例方法上设置了 spy,但绑定的方法(可能是事件处理程序)已经在渲染中使用,因此第一次触发它时,它仍然使用非间谍版本。您需要强制重新渲染以获取间谍方法。无论出于何种原因,component.forceUpdate()wrapper.update() 都无法单独使用,您需要两者。
猜你喜欢
  • 2014-08-08
  • 2017-02-10
  • 2016-09-14
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 2021-06-07
  • 2018-09-27
相关资源
最近更新 更多