首页 > 解决方案 > 如何在 VueJS test-utils parentComponent 中模拟 Vuex 商店

问题描述

我正在Jest尝试vue-test-utils测试子组件是否$emit对父组件中的事件做出反应。

VueJS test-utils 库提供了parentComponent在安装/浅安装组件时传递的选项。

一切正常,除了即使我使用模拟的 Vuex 存储实例化组件,父组件也会抛出一个

TypeError:无法读取未定义的属性“状态”

this.$store.state.something.here父组件中的一段代码上。

我怎样才能在那里模拟 Vuex 商店?

组件挂载如下所示:

const wrapper = shallowMount(ChildComponent, {
  store,
  localVue,
  parentComponent: ParentComponent,
  mocks: {
    $t: msg => msg,
  },
});

关于如何解决这个问题的任何想法?

标签: javascriptvue.jsjestjsvuexnuxt.js

解决方案


它可能不是对 OP 问题的完整答案,但由于我在过去的 2 小时中一直在调试并最终发现了我的问题,所以我想在这里发布以帮助将来的人。

我试图模拟和安装以下组件:

<template>
<div test="object-list-div">
  <h1 test="component-title">{{ objectName }}</h1>
  <table class="table">
    <thead>
        <tr test="table-row-title">
            <th scope="col" test="table-column-title" v-for="(value, name, index) in objectData[0]" :key="index">{{ name }}</th>
        </tr>
    </thead>
    <tbody>
      <tr test="table-row-data" v-for="(ivalue, iname, i) in objectData" :key="i">
        <td test="table-cell-data" v-for="(jvalue, jname, j) in ivalue" :key="j">{{ jvalue }}</td>
      </tr>
    </tbody>
  </table>
</div>

export default  {

    props: [
        'objectName',
        'objectData'
    ],
    computed: {
      visibleColums() {
        return this.$store.state.Config_ShowColumn;
      }
    }
}

使用以下包装代码

 wrapper = shallowMount(ObjectList, {
    mocks: {
      $store: {
        state: {
          Config_ShowColumn: [
            "Field1",
            "Field2",
            "Field3",
            "Field4",
            "Field5",
          ]
        }
      }
    }
  });

我收到了 OP 错误,但在我的情况下,组件在创建时需要两个道具。因为它没有收到这个,所以卡住了。

这正在工作:

import { shallowMount } from "@vue/test-utils";
import { expect } from "chai";
import ObjectList from "@/components/Object-List.vue";  

wrapper = shallowMount(ObjectList, {
    propsData: {
      objectName: "Ticket",
      objectData: [
        {
          Field1: "Field1",
          Field2: "Field2",
          Field3: "Field3",
          Field4: "Field4",
          Field5: "Field5",
        },
      ]
    }, 
    mocks: {
      $store: {
        state: {
          Config_ShowColumn: [
            "Field1",
            "Field2",
            "Field3",
            "Field4",
            "Field5",
          ]
        }
      }
    }
  });

希望它可以帮助某人。


推荐阅读