如何在存根中触发事件? [vue-test-utils]

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

我正在尝试测试这样的组件事件:

// 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

事件调用组件方法的地方。效果很好
但是如果我使用自定义组件,则不会调用组件方法

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

如何解决?

您可以在 my-custom-form 组件上使用 .native 修饰符来侦听本机 DOM 事件而不是自定义 submit 事件。来自 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.

因此以下内容应该适用于您的情况..

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

编辑: 请参阅下面@writofmandamus 的评论和@JaredMcAteer 的回答以获得更好的解决方案。

来自@writofmandamus,在已接受答案的评论中,提供了更通用的使用答案,因为可能无法或不需要将事件绑定更改为 .native

您可以通过以下方式从组件存根发出事件:

wrapper.find('my-custom-component-stub').vm.$emit('custom-event');