0
votes

I'm currently testing vuex module specifically actions.

Here's my code: 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;
   }
};

Then when I test my actions:

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);
  });

when I try to run the test npm run dev it shows the console.log from action but from mutation SET_USERS it doesn't show the console.log

I'm referring to this documentation which I can use spy using sinon() https://vuex.vuejs.org/guide/testing.html

How can I access the commit inside action to call mutation SET_USERS?

1

1 Answers

0
votes

According to sinon docs

A test spy is a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls. There are two types of spies: Some are anonymous functions, while others wrap methods that already exist in the system under test.

const commit = sinon.spy();

That is not the 'commit' from Vuex, you should test your mutation individually

actions.getUsers({ commit, state });

The commit argument is actually the spy, it will never trigger the mutation.

To test your mutation it could be something like this

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