0

I'm having some difficulty using Sinon with bound methods (https://babeljs.io/docs/plugins/transform-class-properties/).

How am I supposed to be attaching spies? Here's a gist: https://gist.github.com/stevens32/b5eee5cc1781a687be03bf80ce8425e0

Which results in:

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
stevens32
  • 314
  • 3
  • 8

1 Answers1

4

You might need to create an instance of the component first. Try this:

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)
})

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

Community
  • 1
  • 1
G Galliani
  • 106
  • 5
  • Thanks! I tried using wrapper.instance() but that also didn't work - looks like reactInstance.forceUpdate() and wrapper.update() did the trick. – stevens32 Feb 21 '17 at 16:50
  • This solved my issue. My suspicion is that, when you shallow render the component, the method bind happens in the component constructor, and the first render pass uses that version. After all that, you set up the spy on the bound instance method, but the bound method (presumably an event handler) has already been used in the render and so the first time its triggered, its still using the non-spied version. You need to force a re-render to pick up the spied method. For whatever reason, `component.forceUpdate()` and `wrapper.update()` each by themselves doesn't cut it and you need both. – webbower Apr 20 '18 at 00:23