Vue Composition API: Unit testing custom events of stubbed child components
That snippet shows how to unit test custom events with event data when using Composition API.
While with Options API you can call wrapper.vm.$emit()
to trigger custom events that is not possible when testing components written with Composition API. For reference check the Vue API documentation.
With Composition API you need to take a reflection like approach for triggering custom events. Fortunately, that approach even works with stubbed components as it is shown below.
Suppose a ContainerComponent.vue
file renders some kind of tab navigation and on the tab itself you want to show a dirty indicator if the content of a tab was changed. The content is realized in child components which emit an event dirty-change
along with a boolean value for its current dirty state. The ContainerComponent
collects those dirty states for each child component and sets it on the prop mark-as-dirty
of the tab component.
When writing a unit test for ContainerComponent
you don't want to mount the NavigationTab
nor the ChildComponents
into the DOM. Yet, you need to test that the mark-as-dirty
prop is set when the child component emits dirty-change
.
The file UnitTestContainerComponent.spec.ts
shows how that is done using the helper function emitOnCustomEvent()
.