2017-04-19 92 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