Skip to content
Snippets Groups Projects

Vue Composition API: Unit testing custom events of stubbed child components

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Robert Wloch

    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().

    Edited
    ChildComponentA.vue 186 B
    ChildComponentB.vue 186 B
    ContainerComponent.vue 624 B
    NavigationTab.vue 210 B
    SomeNavigation.vue 58 B
    UnitTestContainerComponent.spec.ts 2.12 KiB
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment