18

I'm trying to test a component event like this:

// template: <form @submit.prevent="save"></form>
const save = jest.fn()
const wrapper = mount(MyComponent, {methods: { save }})
wrapper.find('form').trigger('submit.prevent')
expect(save).toBeCalled() // Called successfully

Where the event calls a component method. It works very well
But if i use a custom component, the component method isn't called

// template: <my-custom-form @submit="save"></my-custom-form>
const save = jest.fn()
const wrapper = mount(MyComponent, {methods: { save }, stubs: ['my-custom-form']})
wrapper.find('my-custom-form-stub').trigger('submit')
expect(save).toBeCalled() // Expected mock function to have been called, but it was not called.

How to solve it?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Daniel
  • 567
  • 6
  • 20

2 Answers2

31

From @writofmandamus, in the comments of the accepted answer, provided a more general use answer, since changing the event binding to .native may not be possible or desired.

You can emit an event from a component stub with:

wrapper.find('my-custom-component-stub').vm.$emit('custom-event');
JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
3

You can use the .native modifier on the my-custom-form component to listen for the native DOM event instead of a custom submit event. From the docs ..

There may be times when you want to listen directly to a native event on the root element of a component. In these cases, you can use the .native modifier for v-on.

So the following should work in your case ..

<my-custom-form @submit.native.prevent="save"></my-custom-form>

EDIT: See @writofmandamus's comment and @JaredMcAteer's answer below for a better solution.

tony19
  • 125,647
  • 18
  • 229
  • 307
Husam Ibrahim
  • 6,999
  • 3
  • 16
  • 28