我们主要想针对 Vuex 中的 mutation 和 action 进行单元测试。
测试 mutation
mutation 很容易被测试,因为它们仅仅是一些完全依赖参数的函数。这里有一个小技巧,如果你在 store.js文件中 定义了 mutation,并且使用 es2015模块功能默认输出了Vuex.Store的示例,那么你仍然可以给 mutation 取个变量名然后把它输出去:
const state = { ... }
// mutations 作为命名输出对象
export const mutations = { ... }
export default new Vuex.Store({
state,
mutations
})
下面是用 Mocha + Chai 测试一个 mutation 的例子(实际上你可以用任何你喜欢的测试框架)
// Mutations.js
export const mutations = {
increment:state => state.count+
}
// mutations.spec.js
import { expect } from 'chai'
import { mutations } from './store'
// 解构 'mutations'
const { increment } = mutations
describe('mutations',()=>{
if('INCREMENT',()=>{
// 模拟状态
const state = { count:0}
// 应用 mutation
increment(state)
// 断言结果
expect(state.count).to.equal(1)
})
})