0

I'm trying to write a unit test for a VueJS 2 component that has a dynamic component that changes as the state changes.

<template>
    <div>
<component ref="dynamicComponent" id="dynamicComponent" :is="someDynamicType" @custom-event="handleCustomEvent">
</component>
    </div>
</template>

What i'm trying to test is that the parent component is handling the custom-event from the child dynamic component correctly. However, the problem I'm running into is that I cannot seem to get a reference to the child dynamic component.

I've tried

await wrapper.findComponent('#dynamicComponent').vm.$emit("custom-event", {});

and

await wrapper.find({ref: 'dynamicComponent'}).vm.$emit("custom-event", {});

and I also tried using the known type of the dynamic component

await wrapper.findComponent(KnownSubType).vm.$emit("custom-event", {});

but in each case, I get the following error

TypeError: Cannot read properties of undefined (reading '$emit')

Is there another way to obtain the component so that I can emit the custom event or is there another way to trigger the event to test my parent component?

sparky
  • 102
  • 1
  • 7

1 Answers1

0

I ran into a similar problem writing tests using dynamic components. To ensure that the child component was loaded before manipulating it in my tests I had to flush promises. This can be either written manually like in this answer: https://stackoverflow.com/a/65665052/11015616

or

the flush-promises npm library can be used.

const wrapper = mount(SomeComponent, {options});
await flushPromises();
// manipulate child component
lschwalf
  • 11
  • 3