【发布时间】:2017-09-15 15:47:48
【问题描述】:
我正在一个更大的应用程序中为我的 vuejs 组件编写单元测试。我的应用程序状态都在 vuex 存储中,所以我几乎所有的组件都从 vuex 中提取数据。
我找不到为此编写单元测试的工作示例。我找到了
当单独对组件进行单元测试时,您可以使用 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