vue.jsjestjsvue-test-utils

How to trigger an event in stub? [vue-test-utils]


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?


Solution

  • 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.