我有一个具有以下结构的 Vue
组件
// parent-component.vue
<main>
<component :is="my.component" @custom-event="callback"/>
</main>
子组件始终具有以下mixin
// child-shared-mixin.js
export default {
mounted() {
this.$emit('custom-event')
},
}
这是子组件的示例
// child-component.vue
<script>
import { ChildSharedMixin } from 'mixins'
export default {
mixins: [
ChildSharedMixin
],
}
</script>
因此,每当安装子
时,我都会向父级触发一个事件,然后执行回调。
使用 Jest
和 Vue Test Utils
如何测试 mixin
已触发 custom-event
?
最佳答案
emitted() Return an object containing custom events emitted by the Wrapper vm.
https://vue-test-utils.vuejs.org/api/wrapper/#emitted
因此要测试子组件,您可以执行以下操作:
describe('myComponent',()={
it('should trigger custom-event on mounted hook',()=>{
let target=mount(myComponent);
expect(target.emitted()['custom-event']).toBeTruthy();
})
})
为了测试父组件,您可以采取相反的方式 - 通过模拟事件并期望调用回调。看看:
关于testing - 如何测试子组件是否触发了自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53222768/