【发布时间】:2019-07-28 09:15:46
【问题描述】:
我目前正在测试专门针对 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;
}
};
然后当我测试我的行为时:
tests/store/modules/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() 来使用 spy https://vuex.vuejs.org/guide/testing.html
如何访问commit 内部操作以调用突变SET_USERS?
【问题讨论】:
标签: unit-testing vue.js vuex nuxt.js vuex-modules