3

I have a method called testfn in my vue component that gets called whenever event testevt fires. This method contains a call to console.log that clearly shows the method is being called.

When running a test with vue-test-utils, if I create a Sinon spy for the method and call the method directly, the spy correctly detects that the method was called:

const wrapper = mount(MyComponent, {});
var spy = sinon.spy(wrapper.vm, 'testfn');
wrapper.vm.testfn();
expect(spy.called).to.be.true; //(uses the Chai assertion library)

This does not throw an error. However, if I create the same spy, but instead of calling the method directly, I emit the event that calls my method, the method gets called (I can see this because the method contains a call to console.log) but the spy does not register that the method was called. Thus, the following gives an error:

const wrapper = mount(MyComponent, {});
var spy = sinon.spy(wrapper.vm, 'testfn');
wrapper.vm.$emit('testevt');
expect(spy.called).to.be.true; //(uses the Chai assertion library)

What seems to be happening is that testfn itself is not called, but rather, a clone of it is called. Regardless, how can I use a sinon spy to detect whether testfn, or a clone of it, gets called after I emit the testevt event?

1 Answer 1

0

I was trying spying like that today with no success so I switched to:

const spy = sinon.spy()
const wrapper = shallowMount(MyComponent, {localVue, methods: {clicked: spy}})
wrapper.get('button').trigger('click')
expect(spy).to.have.been.calledOnce

Hopefully someone can find an actual answer - but until then this works.

Sign up to request clarification or add additional context in comments.

1 Comment

[vue-test-utils]: overwriting methods via the `methods` property is deprecated and will be removed in the next major version. There is no clear migration path for the `methods` property - Vue does not support arbitrarily replacement of methods, nor should VTU. To stub a complex method extract it from the component and test it in isolation. Otherwise, the suggestion is to rethink those tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.