【问题标题】:Mocking vuex action using and Mocha使用和 Mocha 模拟 vuex 动作
【发布时间】: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


    【解决方案1】:

    根据 sinon 文档

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

    const commit = sinon.spy();

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

    actions.getUsers({ commit, state });
    

    commit 参数实际上是 spy,它永远不会触发突变。

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

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

    【讨论】:

    • 但是为什么来自这个文档呢? vuex.vuejs.org/guide/testing.html 它使用 sinon.spy() 作为提交?如果仍然无法使用 spy 触发突变,你能举个例子,我可以从动作中触发突变吗?
    • 是的,但是看看他们在那里做的期望,他们不是在寻找状态的变化,他们正在寻找传递给间谍的参数。 expect(commit.args).to.deep.equal([ ['REQUEST_PRODUCTS'], ['RECEIVE_PRODUCTS', { /* mocked response */ }] ])
    • 好的,明白了。但是如果我想在不使用 spy 的情况下进行测试呢?有没有办法可以通过测试提交并可以分派操作然后改变状态?您提供的示例是直接调用突变而不是操作
    • 您可以在测试中创建一个新的 Vuex 实例,包含您的操作、突变和状态,here is an example
    猜你喜欢
    • 2018-04-22
    • 2015-12-16
    • 2016-10-27
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2016-10-11
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多