Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 461
Daniel Avatar asked Nov 23 '18 13:11

Daniel


People also ask

What are stubs in Vue test utils?

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.

Does Vue test utils use jest?

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.

What is createLocalVue?

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 utils in Vue?

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.


1 Answers

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');
like image 129
JaredMcAteer Avatar answered Sep 19 '22 14:09

JaredMcAteer