2017-04-19 116 views
8

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

我找不到一个为此编写单元测试的工作示例。我发现

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.

但我无法找到如何测试这些组件一个很好的例子。我尝试了很多方法。以下是我看到人们这样做的唯一途径。 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); 
    }); 
} 

注意 “裁判” 这个例子不无它的工作。

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

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

你是怎么做的?

+0

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

回答

10

答案其实很简单,但目前没有记录。

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-仙丹-的WebPack官方所致。
如果你做了修正:

npm install [email protected] --save-dev

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

你的测试,包括Vuex似乎即使你有Vue.use(Vuex)与

[vuex] must call Vue.use(Vuex)

打破

+0

这似乎有效,但我有点担心它依赖于API的未公开的方面。有没有人有任何天气信息这是支持或替代方法? – d512