测试组件--挂载的钩子出错:"TypeError.Canot read property 'dispatch' of undefined"。无法读取未定义的'dispatch'属性"

问题描述 投票:0回答:1

我试图为我的vue组件写一个简单的测试。由于vue组件在挂载时进行异步调用并更新vuex存储。dispatch 在挂载过程中被调用,这破坏了我现有的单元测试。有什么办法可以克服这个问题吗?因为我是在模拟表数据,所以我不需要在运行测试时调用 mounted()函数。

MyTable.spec.js

     const wrapper = shallowMount(MyTable, {
        propsData: {
            tableData: [
                {
                    "product_id":10826345236,
                    "name":"T-Shirt"
                }
            ],
            columns: ['product_id', 'name'],
            headings: ['Product ID', 'Name'],
            actionType: 'loadProducts'
        }
    });
    ...

MyTable.vue

    ...
    data() {
        return {
            options: {
                ...
            }
        };
    },
    methods: {
        getHeadings() {
            let headings = {};
            this.columns.map((key, i) => headings[key] = this.headings[i]);
            return headings;
        },
        setColumnClasses() {
            let classes = {};
            this.columns.map((key) => classes[key] = key);
            return classes;
        },
        loadRecords(actionType) {
            this.$store.dispatch(actionType);
        }
    },
    props: {
        tableData: {
            type: Array,
            required: true
        },
        columns: {
            type: Array,
            required: true
        },
        actionType: {
            type: String,
            required: true
        },
        headings: {
            type: Array,
            required: true
        },
        ...
    },
    mounted() {
        this.loadRecords(this.actionType);
    }
javascript vue.js vuex vue-test-utils
1个回答
0
投票

你得到这个错误信息是因为Vue(在挂载时)希望在挂载过程中的 this.$store 的定义,虽然它可能在你的应用程序中,但你并没有导入它,也没有模拟它。

这是你提供的测试函数代码。

const wrapper = shallowMount(MyTable, {
  propsData: {
    tableData: [
      {
        "product_id":10826345236,
        "name":"T-Shirt"
      }
    ],
    columns: ['product_id', 'name'],
    headings: ['Product ID', 'Name'],
    actionType: 'loadProducts'
  }
});

这里是你需要添加的内容

import store from '../path/to/store.js';
import { createLocalVue, shallowMount } from '@vue/test-utils';

// You will want to create a local Vue instance for testing purposes: https://vue-test-utils.vuejs.org/api/#createlocalvue
const localVue = createLocalVue();

// This tells the local Vue instance to use Vuex for the store mechanism.
localVue.use(Vuex);

const wrapper = shallowMount(MyTable, {
  localVue, // Bind the local Vue instance when we shallow-mount the component.
  store, // Bind the store so all of the methods are available when invoked.
  propsData: {
    tableData: [
      {
        "product_id":10826345236,
        "name":"T-Shirt"
      }
    ],
    columns: ['product_id', 'name'],
    headings: ['Product ID', 'Name'],
    actionType: 'loadProducts'
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.