Find the Vue.js 2 version .

Testing mutations in isolation is very straight forward, because mutations are just regular JavaScript functions. This page discusses testing mutations in isolation. If you want to test mutations in the context of a component committing a mutation, see here.

The test used in the following example can be found .

Mutations tend to following a set pattern. Get some data, maybe do some processing, then assign the data to the state. Here is the outline of an mutation. Once implemented, it will receive a post object in the payload, and add the post.id to state.postIds. It will also add the post object to the state.posts object, where the key is the post.id. This is a common pattern in apps using Vuex.

Let’s write the test, and let the error messages guide our development:

  1. import mutations from "@/store/mutations.js"
  2. describe("SET_POST", () => {
  3. it("adds a post to the state", () => {
  4. const post = { id: 1, title: "Post" }
  5. const state = {
  6. postIds: [],
  7. posts: {}
  8. mutations.SET_POST(state, { post })
  9. expect(state).toEqual({
  10. postIds: [1],
  11. posts: { "1": post }
  12. })
  13. })
  14. })

Running this test with yarn test:unit yields the following failure message:

Let’s start by adding the post.id to state.postIds:

  1. export default {
  2. state.postIds.push(post.id)
  3. }

Now yarn test:unit yields:

  1. export default {
  2. SET_POST(state, { post }) {
  3. state.postIds.push(post.id)
  4. state.posts = { ...state.posts, [post.id]: post }
  5. }

Now the test passes!

Testing Vuex mutations requires nothing specific to Vue or Vuex, since they are just regular JavaScript functions. Simply import them and test as needed. The only thing to be careful of is Vue’s reactivity caveats, which apply to Vuex as well. You can read more about the reactivity system and common caveats here.

The page discussed:

  • Vuex mutations are regular JavaScript functions

The test used in the above example can be found .