如何测试子组件触发了自定义事件

How to test that a custom event from was fired from child component

我有一个具有以下结构的 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>

因此,每当挂载 child 时,我都会向父级触发一个事件,然后执行回调。

使用 JestVue 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();
    })
})

要测试父组件,您可以采用相反的方式 - 通过模拟事件并期望回调被调用。看看:

https://vue-test-utils.vuejs.org/api/wrapper/trigger.html