我正在爲更大的應用程序中的vuejs組件編寫單元測試。我的應用程序狀態都在vuex存儲中,所以幾乎所有的組件都從vuex中提取數據。如何在使用Vuex時測試Vuejs組件
我找不到一個爲此編寫單元測試的工作示例。我發現
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的引用似乎暗示商店可以直接添加到子組件(即不像示例中的父級)。
你是怎麼做的?
此方法不適用於js的bable-loader,但適用於js的buble loader。錯誤總是錯誤的:[vuex]必須調用Vue.use(Vuex),即使使用Vue.use(Vuex),同時使用import vue和require vue。 –