首页 > 解决方案 > 如何在存根中触发事件?[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.

如何解决?

标签: vue.jsjestjsvue-test-utils

解决方案


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

您可以使用以下组件从组件存根发出事件:

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

推荐阅读