ebb*_*hop 4 javascript unit-testing vue.js jestjs vue-test-utils
我有一组父子 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>
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的一件事:
父规范.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();
})
})
Run Code Online (Sandbox Code Playgroud)
上面的测试失败了,我不知道为什么。
我还尝试过以下测试:
// 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)
Run Code Online (Sandbox Code Playgroud)
这些也会失败 - 就好像事件根本没有被触发(是这样吗?),或者我正在尝试测试一些不可能的东西。
是否有一种可接受的方法来测试父组件对子组件发出的事件的处理?
trigger()仅适用于本机 DOM 事件。对于自定义事件,请使用wrapper.vm.$emit()(并且不需要await):
// await parent.findComponent(ChildComponent).trigger(\'customEvent\', 2);\n// ^^^^^^^ \xe2\x9d\x8c\n\nparent.findComponent(ChildComponent).vm.$emit(\'customEvent\', 2);\nRun Code Online (Sandbox Code Playgroud)\nVue 2 不支持从实例中监视方法,因此需要在安装之前对组件定义( )wrapper.vm进行监视:Parent.methods
// const spy = jest.spyOn(parent.vm, \'customEventHandler\');\n// ^^^^^^^^^ \xe2\x9d\x8c not supported in Vue 2\n\nconst spy = jest.spyOn(Parent.methods, \'customEventHandler\')\nconst parent = mount(Parent)\nRun Code Online (Sandbox Code Playgroud)\n\n请注意,Vue 3确实支持通过wrapper.vm.