[英]Testing Vue with Jest: custom event handled by parent, emitted by child component
I have a set of parent & child vue components.我有一组父子 vue 组件。 The child emits an event that the parent handles.孩子发出一个由父母处理的事件。 I'd like to test that it handles the custom event correctly, but I am stuck.我想测试它是否正确处理自定义事件,但我被卡住了。
Parent.vue父.vue
<template>
<div id="app" class="container">
<!-- phonebook -->
<ChildComponent
class="row mt-4"
@customEvent="val => customEventHandler(val)"
></ChildComponent>
</div>
</template>
<script>
import ChildComponent from './components/ChildComponent.vue'
export default {
name: 'App',
components: {
ChildComponent,
},
data() {
return {
test: [1, 2, 3, 4]
};
},
methods: {
customEventHandler(id) {
// removes item `id` from the `test` array
this.test = this.test.filter((item) => item !== id);
},
}
};
</script>
This is one thing I've tried:这是我尝试过的一件事:
Parent.spec.js父规范.js
import { mount, shallowMount } from "@vue/test-utils";
import Parent from '../../src/Parent.vue';
import ChildComponent from '../../src/components/ChildComponent.vue';
describe('customEvent event', () => {
beforeEach(() => {
parent = mount(Parent, {
data() {
return {
test: [1, 2, 3, 4]
};
},
});
});
it('should trigger the customEventHandler method', async() => {
const spy = jest.spyOn(parent.vm, 'customEventHandler');
await parent.findComponent(ChildComponent).trigger('customEvent', 2);
expect(spy).toHaveBeenCalled();
})
})
The test above fails and I'm not sure why.上面的测试失败了,我不知道为什么。
I've also tried the following tests:我还尝试了以下测试:
// check what the spy has been called with
expect(spy).toHaveBeenCalledWith(2);
// test the side-effects of the `customEventHandler` method
expect(parent.vm.test.length).toEqual(3)
These also fail - it's as though the event isn't being triggered at all (is that it?), or I'm trying to test something that isn't possible.这些也失败了——就好像事件根本没有被触发(是这样吗?),或者我正在尝试测试一些不可能的东西。
Is there an accepted way to test a parent component's handling of an event emitted by a child component?是否有一种公认的方法来测试父组件对子组件发出的事件的处理?
trigger()
only works for native DOM events. trigger()
仅适用于原生 DOM 事件。 For custom events, use wrapper.vm.$emit()
(and no need to await
it):对于自定义事件,使用wrapper.vm.$emit()
(无需await
它):
// await parent.findComponent(ChildComponent).trigger('customEvent', 2);
// ^^^^^^^ ❌
parent.findComponent(ChildComponent).vm.$emit('customEvent', 2);
Vue 2 does not support spying on methods from the wrapper.vm
instance, so the spying needs to be done on the component definition ( Parent.methods
) before mounting : Vue 2 不支持对wrapper.vm
实例中的方法进行监视,因此需要在挂载之前对组件定义( Parent.methods
)进行监视:
// const spy = jest.spyOn(parent.vm, 'customEventHandler');
// ^^^^^^^^^ ❌ not supported in Vue 2
const spy = jest.spyOn(Parent.methods, 'customEventHandler')
const parent = mount(Parent)
Note that Vue 3 does support spying via wrapper.vm
.请注意,Vue 3确实支持通过wrapper.vm
进行间谍活动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.