testing - 如何测试子组件是否触发了自定义事件

标签 testing vue.js jestjs vue-test-utils

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

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

使用 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

关于testing - 如何测试子组件是否触发了自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53222768/

相关文章:

c++ - 谷歌测试框架 - 测试用例之间的依赖关系

javascript - 绑定(bind)子输入:value to the parent prop

javascript - 使用 --detectOpenHandles --forceExit 运行 jest 是否有副作用?

reactjs - React、TypeScript 和 RxJS 测试与 Jest 不工作

java - 使用多个套件进行测试。 @AfterSuite 方法在第一个套件和第二个套件无法运行后关闭驱动程序

django - 模型验证 : can I access ValidationError code?

c# - 如何测试C#传真程序?

javascript - 通过 cloudflare 提供的对 vue 资源的 Ajax 响应数据未从 Chrome 中的 json 解析

javascript - 如何解决需要适当加载器的 npm 错误?

javascript - 开 Jest 和console.dir不会显示整个对象