unit-testing - 使用和 Mocha 模拟 vuex 动作
问题描述
我目前正在测试专门针对 vuex 模块的操作。
这是我的代码: store/modules/users.js
export const state = () => ({
users: [],
})
export const mutations = () => ({
SET_USERS(state, users) {
console.log('Should reach Here');
state.users = users
}
})
export const actions = () => ({
getUsers({ commit }) {
return axios.get('/users')
.then(response => {
console.log('Reaching Here');
commit('SET_USERS', response.data.data.results)
})
.catch(error => {
console.log(error);
})
}
})
export const getters = () => {
users(state) {
return state.users;
}
};
然后当我测试我的动作时:
测试/商店/模块/users.js
it('should dispatch getUsers', () => {
mock.onGet('/users').reply(200, {
data: {
results: [
{ uid: 1, name: 'John Doe' },
{ uid: 2, name: 'Sam Smith' }
]
},
status: {
code: 200,
errorDetail: "",
message: "OK"
}
});
const commit = sinon.spy();
const state = {};
actions.getUsers({ commit, state });
expect(getters.users(state)).to.have.lengthOf(2);
});
当我尝试运行测试npm run dev
时,它从操作中显示 console.log,但从突变SET_USERS
中它不显示 console.log
我指的是这个文档,我可以使用 sinon() https://vuex.vuejs.org/guide/testing.html使用 spy
如何访问commit
内部操作来调用突变SET_USERS
?
解决方案
根据 sinon 文档
测试间谍是一个函数,它记录所有调用的参数、返回值、this 的值和抛出的异常(如果有的话)。有两种类型的间谍:一些是匿名函数,而另一些则封装了被测系统中已经存在的方法。
const commit = sinon.spy();
这不是来自 Vuex 的“提交”,您应该单独测试您的突变
actions.getUsers({ commit, state });
提交参数实际上是间谍,它永远不会触发突变。
为了测试你的突变,它可能是这样的
mutations.SET_USERS(state, mockedUsers)
expect(state).to.have.lengthOf(mockedUsers.length)
...
推荐阅读
- ios - AWS Cognito - 通过电话号码获取用户
- android - 如何检测 NFC P2P 事件
- python-2.7 - 如果路径中有空格,Python服务器无法访问文件
- google-chrome - 量角器测试在 chrome 中失败
- apache-spark - 带有 Spark 的 Mesos - 无法使用外部随机播放服务注册应用程序
- c# - 注册一个 X509Certificate2 而不会在机器上留下任何痕迹
- python - str.count() 错了吗?
- php - 将数据填充到数组并在 PHP 中继续迭代
- python - Django:list_display 不可调用
- android - android studio中没有导航编辑器