waghcwb
waghcwb

Reputation: 387

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

I've a Vue component with the following structure

// parent-component.vue
<main>
  <component :is="my.component" @custom-event="callback"/>
</main>

The child component has always have the following mixin

// child-shared-mixin.js
export default {
  mounted() {
    this.$emit('custom-event')
  },
}

Here is the example of the child component

// child-component.vue
<script>
  import { ChildSharedMixin } from 'mixins'

  export default {
    mixins: [
      ChildSharedMixin
    ],
  }
</script>

So, whenever the child is mounted I trigger a event to the parent and then execute a callback.

With Jest and Vue Test Utils how can I test that mixin has fired the custom-event?

Upvotes: 2

Views: 3617

Answers (1)

Efrat Levitan
Efrat Levitan

Reputation: 5612

emitted() Return an object containing custom events emitted by the Wrapper vm.

https://vue-test-utils.vuejs.org/api/wrapper/#emitted

so to test the child component, you can do:

describe('myComponent',()={
    it('should trigger custom-event on mounted hook',()=>{
        let target=mount(myComponent);
        expect(target.emitted()['custom-event']).toBeTruthy();
    })
})

and to test the parent component, you go the other way around- by mocking the event and expecting the callback to get invoked. take a look at:

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

Upvotes: 3

Related Questions