在使用Vuex时如何测试Vuejs组件

Pat*_*ane 8 components unit-testing vue.js vuex

我正在为更大的应用程序中的vuejs组件编写单元测试.我的应用程序状态全部在vuex存储中,因此几乎所有组件都从vuex中提取数据.

我找不到为此编写单元测试的工作示例.我已经找到

Evan You说的地方:

单独测试组件时,可以使用store选项将模拟存储直接注入组件.

但我找不到如何测试这些组件的好例子.我尝试了很多方法.以下是我见过人们做的唯一方法.stackoverflow问答

基本上它看起来像

test.vue:

 <template>
    <div>test<div>
 </template>
 <script>
 <script>
    export default {
        name: 'test',
        computed: {
            name(){
                return this.$store.state.test;
            }
        }
    }
  </script>
Run Code Online (Sandbox Code Playgroud)

test.spec.js

import ...

const store = new Vuex.Store({
  state: {
    test: 3
  }
});
describe('test.vue', () => {

  it('should get test from store', () => {

    const parent = new Vue({
      template: '<div><test ref="test"></test></div>',
      components: { test },
      store: store
    }).$mount();

    expect(parent.$refs.test.name).toBe(3);
  });
}
Run Code Online (Sandbox Code Playgroud)

注意"ref"这个例子没有它就行不通.

这真的是正确的方法吗?看起来它会变得很乱,因为它需要将道具添加到模板中作为字符串.

Evan的引用似乎暗示商店可以直接添加到子组件(即不像示例那样的父组件).

你是怎样做的?

Pat*_*ane 10

答案实际上非常简单,但目前没有记录.

  const propsData = { prop: { id: 1} };
  const store = new Vuex.Store({state, getters});

  const Constructor = Vue.extend(importedComponent);
  const component = new Constructor({ propsData, store });
Run Code Online (Sandbox Code Playgroud)

注意商店传递给构造函数.propsData目前已记录,"store"选项不是.

此外,如果您使用的是Laravel,那么您可能正在运行的webpack版本存在一些奇怪的问题.

[vuex]必须调用Vue.use(Vuex),

使用laravel-elixir-webpack-official导致错误.
如果你做了修复:

npm install webpack@2.1.0-beta.22 --save-dev

为此https://github.com/JeffreyWay/laravel-elixir-webpack-official/issues/17

你的测试包括Vuex似乎打破了

[vuex]必须调用Vue.use(Vuex)

即使你有Vue.use(Vuex)