vue.js - 如何在存根中触发事件?[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.
如何解决?
解决方案
来自@writofmandamus,在已接受答案的评论中,提供了更通用的答案,因为.native
可能无法或不需要将事件绑定更改为。
您可以使用以下组件从组件存根发出事件:
wrapper.find('my-custom-component-stub').vm.$emit('custom-event');
推荐阅读
- c++ - 为什么派生类中的虚函数也是虚函数?
- html - 将 div 放在具有内容包装器动态高度的容器底部
- c++ - 如何从 unicode 字符串中获取单个字符并比较、打印它们?
- html - Angular HTML - 基于布尔值更改表格单元格背景颜色
- javascript - 如何捕获在快速路由器中找不到的页面
- javascript - 如何对reduce对象中的特定元素求和?
- google-cloud-platform - GKE Ingress 不使用 cert-manager ssl secrets
- swagger - 如何找到公司的 OpenAPI 规范?
- reactjs - 反应路由器和链接都指向同一页面?
- javascript - 我无法从 firebase 数据库中获取数据