【问题标题】:How do you test Vuejs Components when using Vuex使用 Vuex 时如何测试 Vuejs 组件
【发布时间】:2017-09-15 15:47:48
【问题描述】:

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

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

Where Evan You says:

当单独对组件进行单元测试时,您可以使用 store 选项将模拟存储直接注入到组件中。

但我找不到如何测试这些组件的好例子。我尝试了很多方法。以下是我看到人们这样做的唯一方法。 stackoverflow question and answer

基本上它看起来像

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 的引用似乎暗示可以将 store 直接添加到子组件(即不像示例中的父组件)。

你是怎么做到的?

【问题讨论】:

  • 此方法不适用于 js 的 bable-loader,但适用于 js 的 buble loader。错误总是错误:[vuex] 必须调用 Vue.use(Vuex),即使使用 Vue.use(Vuex),同时使用 import vue 和 require vue。

标签: unit-testing vue.js components vuex


【解决方案1】:

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

  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] 必须调用 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)

【讨论】:

  • 这似乎确实有效,但我有点担心它依赖于 API 的未记录方面。有没有人有任何关于天气的信息,这是支持的或替代方法?
猜你喜欢
  • 2017-07-21
  • 2020-06-23
  • 2023-04-03
  • 2018-05-07
  • 2018-12-13
  • 2020-03-14
  • 2017-12-09
  • 2017-10-04
  • 2021-01-06
相关资源
最近更新 更多