如何使用Jest测试具有子组件的Vue组件

时间:2020-07-07 08:25:04

标签: javascript vue.js testing jestjs components

我是前端测试的新手,现在已经花了两天多的时间来测试组件而没有取得任何进展。

我的组件 CreateStoryForm 看起来像这样:

<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 是一个简单的自定义组件,已在 main.js 中全局注册。

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

我现在想用Jest测试Form组件,并查看按下按钮时是否发出了“取消”事件。但是,只有在使用默认按钮标签而不是自定义BaseButtonText组件时,我才能使它工作。

我尝试过的事情:

  1. 使用存根:

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

-> wrapper.find('base-btn-text-stub').trigger('click');不发出事件

  1. 在实现中使用存根:

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

-> wrapper.find('base-btn-text-stub');wrapper.find('base-btn-text');不返回任何内容

  1. 在测试本身中导入和注册子组件:

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

-> wrapper.find(BaseButtonText).trigger('click');不发出事件

现在我完全迷路了。

0 个答案:

没有答案
相关问题