我有一组父子 vue 组件。 child 发出一个由 parent 处理的事件。我想测试它是否正确处理自定义事件,但我被卡住了。
父.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>
这是我尝试过的一件事:父规范.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();
})
})
上面的测试失败了,我不知道为什么。我还尝试了以下测试:
// 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)
这些也失败了——就好像事件根本没有被触发(是这样吗?),或者我正在尝试测试一些不可能的东西。是否有一种公认的方法来测试父组件对子组件发出的事件的处理?
最佳答案
触发事件
trigger()
仅适用于 native DOM 事件。对于自定义事件,请使用 wrapper.vm.$emit()
(并且不需要 await
它):
// await parent.findComponent(ChildComponent).trigger('customEvent', 2);
// ^^^^^^^ ❌
parent.findComponent(ChildComponent).vm.$emit('customEvent', 2);
监视方法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)
demo请注意,Vue 3 确实支持通过
wrapper.vm
进行监视。 .
关于javascript - 使用子组件发出的 Jest : custom event handled by parent, 测试 Vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65997114/