使用 Vuex 时如何测试 Vuejs 组件

How do you test Vuejs Components when using Vuex

我正在为大型应用程序中的 vuejs 组件编写单元测试。我的应用程序状态都在 vuex 存储中,所以我几乎所有的组件都从 vuex 中拉取数据。

我找不到为此编写单元测试的工作示例。我找到了

Where Evan You says:

When unit testing a component in isolation, you can inject a mocked store directly into the component using the store option.

但是我找不到一个很好的例子来说明如何测试这些组件。我尝试了很多方法。以下是我见过人们这样做的唯一方法。

基本上看起来像

test.vue:

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

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);
  });
}

请注意 "ref" 这个例子没有它就无法工作。

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

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

你是怎么做到的?

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

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

  const Constructor = Vue.extend(importedComponent);
  const component = new Constructor({ propsData, store });

注意传递给构造函数的商店。 propsData 目前是 documented,"store" 选项不是。

此外,如果您正在使用 Laravel,您可能 运行 的 webpack 版本存在奇怪的问题。

[vuex] must call 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] must call Vue.use(Vuex)

即使你有 Vue.use(Vuex)