mardi 7 juillet 2020

How to test a Vue component that has a child component with Jest

I'm new to frontend testing and I've now spent more than two day trying to test a component without making any progress.

My component CreateStoryForm looks like this:

<template>
  <v-card>
    <v-card-title>Title</v-card-title>
    <v-card-text>
      <v-form>
        <base-btn-text
          @click="cancel()"
          class=cancel
        >
          Cancel
        </base-btn-text>
      </v-form>
    </v-card-text
  </v-card>
</template>

<script>
  ...
  methods: {
    cancel() {
        this.$emit('cancel');
    },
  }
</script>

base-btn-text is a simple a custom component that is registered globally in main.js.

Vue.component('base-btn-text, BaseButtonText);

I now want to test the Form component with Jest and see if the event 'cancel' is emitted when pressing the button. However I can only make it work when I use a default button tag instead of my custom BaseButtonText-component.

What I tried:

  1. Using a stub:

     wrapper = shallowMount(CreateStoryForm, {
       ...
       stubs: {
         'base-btn-text': true
      }
    

-> wrapper.find('base-btn-text-stub').trigger('click'); does not emit an event

  1. Using a stub with implementation:

     const CancelButton = "<button @click='cancel()'>Cancel</button>"
     ...
     wrapper = shallowMount(CreateStoryForm, {
       ...
       stubs: {
         'base-btn-text': CancelButton
      }
    

-> wrapper.find('base-btn-text-stub'); or wrapper.find('base-btn-text'); does not return anything

  1. Importing and registering the child component in the test itself:

     import BaseButtonText ...
     Vue.component('base-btn-text, BaseButtonText);
    

-> wrapper.find(BaseButtonText).trigger('click'); does not emit an event

And now I'm completely lost.

Aucun commentaire:

Enregistrer un commentaire