我正在为更大的应用程序中的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。 –