【问题标题】:How to test that a custom event from was fired from child component如何测试从子组件触发的自定义事件
【发布时间】:2019-04-12 20:22:05
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    emitted() 返回一个包含由 包装器虚拟机。

    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

    【讨论】:

    • 谢谢,问题是我没有测试子组件。
    • 因为这个特定的事件发生在挂载的钩子上,你不必模拟它。只要确保它真的发生了,用你自己的存根覆盖回调并检查它是否被调用:describe('parent',()={ it('should trigger custom-event on mounted hook',()=&gt;{ lat callback=sinon.stub(); let options={ methods:{ callback, } } let target=mount(parent,options); expect(callback.called).toBe(true); }) })
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多