首页 > 解决方案 > 使用和 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

标签: unit-testingvue.jsvuexnuxt.jsvuex-modules

解决方案


根据 sinon 文档

测试间谍是一个函数,它记录所有调用的参数、返回值、this 的值和抛出的异常(如果有的话)。有两种类型的间谍:一些是匿名函数,而另一些则封装了被测系统中已经存在的方法。

const commit = sinon.spy();

这不是来自 Vuex 的“提交”,您应该单独测试您的突变

actions.getUsers({ commit, state });

提交参数实际上是间谍,它永远不会触发突变。

为了测试你的突变,它可能是这样的

mutations.SET_USERS(state, mockedUsers)
expect(state).to.have.lengthOf(mockedUsers.length)
...

推荐阅读