如何在VueJS测试实用程序parentComponent中模拟Vuex存储 [英] How to mock a Vuex store in VueJS test-utils parentComponent

查看:266
本文介绍了如何在VueJS测试实用程序parentComponent中模拟Vuex存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Jestvue-test-utils结合使用,试图测试子组件是否对父组件中的$emit事件做出反应.

I'm using Jest with vue-test-utils trying to test if a child component reacts to an $emit event in the parent component.

VueJS测试实用程序库提供了parentComponent选项,该选项可在安装/浅装组件时通过.

VueJS test-utils library provides a parentComponent option to be passed when mounting/shallow mounting the component.

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

Everything is working fine except that even though I instantiate the component with a mocked Vuex store, the parent component throws a

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

TypeError: Cannot read property 'state' of undefined

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

on a this.$store.state.something.here piece of code in the parent component.

如何模拟那里的Vuex商店?

How can I mock the Vuex store there?

组件安装看起来像这样:

The component mount looks like this:

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

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

Any ideas on how to solve this?

推荐答案

尝试了Richard提出的解决方案,但即使他的猜测是正确的,也没有太大的成功.

Tried the solution Richard proposed but without much success, even though his guess was right.

解决方案远比我想象的要简单,我只是停止实例化Vuex.Store,而在vue-test-utils config中仅模拟了$store,就像这样:

The solution was far simnpler than I envisioned, I just stopped instantiating the Vuex.Store and just have the mocked $store in vue-test-utils config like so:

import { createLocalVue, shallowMount, config } from '@vue/test-utils';

config.mocks.$store = {
  state: {
    user: {
      sexy: true
    },
  },
};

我不需要使用Vuex的实际实例,因为我只需要模拟实际数据,因此可以完美地工作.

I had no need to use an actual instance of Vuex as I only needed to mock the actual data so this worked perfectly.

这篇关于如何在VueJS测试实用程序parentComponent中模拟Vuex存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆