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?
Vue Test Utils provides some advanced features for stubbing components and directives. A stub is where you replace an existing implementation of a custom component or directive with a dummy one that doesn't do anything at all, which can simplify an otherwise complex test. Let's see an example.
If you are using the Vue CLI to build your project, you can use the plugin cli-plugin-unit-jest to run Jest tests. The plugin pulls all required dependencies (including jest), creates a jest. config.
createLocalVue returns a Vue class for you to add components, mixins and install plugins without polluting the global Vue class. The errorHandler option can be used to handle uncaught errors during component render function and watchers.
What is Vue Test Utils? Vue Test Utils (VTU) is a set of utility functions aimed to simplify testing Vue. js components. It provides some methods to mount and interact with Vue components in an isolated manner.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With