Find the Vue.js 3 version .

The previous guide discussed testing components that use and $store.getters, which both provide the current state to the component. When asserting a component correctly commits a mutation or dispatches an action, what we really want to do is assert $store.commit and $store.dispatch is called with the correct handler (the mutation or action to call) and payload.

There are two ways to go about this. One is to use a real Vuex store with createLocalVue, and another is to use a mock store. Both these techniques are demonstrated here. Let’s see them again, in the context of mutations and actions.

The source code for the test described on this page can be found .

Creating the Component

For these examples, we will test a <ComponentWithButtons> component:

  1. Did the correct mutation get committed?
  2. Was the payload correct?

We will use createLocalVue to avoid polluting the global Vue instance.

Notice the tests are marked await and call nextTick. See here for more details on why.

There is a lot code in the test above - nothing too exciting is happening, though. We create a and use Vuex, then create a store, passing a Jest mock function (jest.fn()) in place of the testMutation. Vuex mutations are always called with two arguments: the first is the current state, and the second is the payload. Since we didn’t declare any state for the store, we expect it to be called with an empty object. The second argument is expected to be { msg: "Test Commit" }, which is hard coded in the component.

This is a lot of boilerplate code to write, but is a correct and valid way to verify components are behaving correctly. Another alternative that requires less code is using a mock store. Let’s see how to do that for while writing a test to assert testAction is dispatched.

Testing using a mock store

Let’s see the code, then compare and contrast it to the previous test. Remember, we want to verify:

  1. the payload is correct

Whether you use a real store or a mock store is your tests is down to personal preference. Both are correct. The important thing is you are testing your components.

The third and final example shows another way to test that an action was dispatched (or mutation committed) with the correct arguments. This combined both techniques discussed above - a real Vuex store, and a mocked dispatch method.

We start by creating a Vuex store, with the module(s) we are interested in. I declare the module namespacedModule inside the test, but in a real world app, you would just import the modules your component depends on. We then replace the dispatch method with a jest.fn mock, and make assertions against that.

Conclusion

In this section we covered:

  1. Using Vuex with a localVue and mocking a mutation
  2. Mocking the Vuex API (dispatch and commit)

The source code for the test described on this page can be found .