Dan*_*iel 6 vue.js jestjs 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
Run Code Online (Sandbox Code Playgroud)
事件在哪里调用组件方法。它工作得很好,
但是如果我使用自定义组件,则不会调用component方法
// 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.
Run Code Online (Sandbox Code Playgroud)
怎么解决呢?
Jar*_*eer 21
来自@writofmandamus,在已接受答案的评论中,提供了更通用的使用答案,因为.native可能无法或不希望将事件绑定更改为。
您可以从组件存根发出事件:
wrapper.find('my-custom-component-stub').vm.$emit('custom-event');
Run Code Online (Sandbox Code Playgroud)
您可以在组件.native上使用修饰符my-custom-form来侦听本机 DOM 事件而不是自定义submit事件。从文档中..
有时您可能想直接监听组件根元素上的本机事件。在这些情况下,您可以使用
.native修饰符 forv-on。
所以以下内容应该适用于您的情况..
<my-custom-form @submit.native.prevent="save"></my-custom-form>
Run Code Online (Sandbox Code Playgroud)
编辑:请参阅下面的@writofmandamus 的评论和@JaredMcAteer 的答案以获得更好的解决方案。
| 归档时间: |
|
| 查看次数: |
1010 次 |
| 最近记录: |