【问题标题】:How to trigger an event in stub? [vue-test-utils]如何在存根中触发事件? [vue-test-utils]
【发布时间】:2019-04-26 02:54:09
【问题描述】:

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

// 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.js jestjs vue-test-utils


    【解决方案1】:

    您可以在my-custom-form 组件上使用.native 修饰符来侦听本机DOM 事件,而不是自定义submit 事件。来自docs..

    有时您可能想直接收听原生事件 在组件的根元素上。在这些情况下,您可以使用 .native 修饰符为v-on

    所以以下应该适用于你的情况..

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

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

    【讨论】:

    • 其实我在做&lt;form @submit.prevent="$emit('submit')"&gt; ... &lt;/form&gt; 但它不起作用。现在我测试了&lt;my-custom-form @submit.native.prevent="save"&gt;&lt;/my-custom-form&gt;,它对我有用。请编辑您的答案
    • @Daniel 好的,我将编辑我的答案。这很奇怪,因为我希望这两种方法都可以工作:\
    • 第一种方法在应用中有效,只有在单元测试中无效
    • 所以我们不能使用非本地事件进行测试?我宁愿不必更改我的代码来进行测试。
    • 看起来你应该像wrapper.find('my-custom-form-stub').vm.$emit('submit')一样使用它
    【解决方案2】:

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

    你可以从一个组件存根发出一个事件:

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

    【讨论】:

    • 是的,这应该是正确的答案,因为您不想更改组件本身。
    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 2020-06-17
    • 2021-09-19
    • 1970-01-01
    • 2019-10-06
    • 2021-04-05
    • 1970-01-01
    • 2019-09-08
    相关资源
    最近更新 更多