This book is written for Vue.js 2 and Vue Test Utils v1.

Find the Vue.js 3 version here.

Testing Actions

Testing actions in isolation is very straight forward. It is very similar to testing mutations in isolation - see hereVuex - Actions - 图1 for more on mutation testing. Testing that a component is correctly dispatching actions is discussed hereVuex - Actions - 图2.

The source code for the test described on this page can be found hereVuex - Actions - 图3.

Creating the Action

We will write an action that follows a common Vuex pattern:

  1. make an asynchronous call to an API
  2. do some proccessing on the data (optional)
  3. commit a mutation with the result as the payload

This is an authenticate action, which sends a username and password to an external API to check if they are a match. The result is then used to update the state by committing a SET_AUTHENTICATED mutation with the result as the payload.

  1. import axios from "axios"
  2. export default {
  3. async authenticate({ commit }, { username, password }) {
  4. const authenticated = await axios.post("/api/authenticate", {
  5. username, password
  6. })
  7. commit("SET_AUTHENTICATED", authenticated)
  8. }
  9. }

The action test should assert:

  1. was the correct API endpoint used?
  2. is the payload correct?
  3. was the correct mutation committed with the result

Let’s go ahead and write the test, and let the failure messages guide us.

Writing the Test

  1. describe("authenticate", () => {
  2. it("authenticated a user", async () => {
  3. const commit = jest.fn()
  4. const username = "alice"
  5. const password = "password"
  6. await actions.authenticate({ commit }, { username, password })
  7. expect(url).toBe("/api/authenticate")
  8. expect(body).toEqual({ username, password })
  9. expect(commit).toHaveBeenCalledWith(
  10. "SET_AUTHENTICATED", true)
  11. })
  12. })

Since axios is asynchronous, to ensure Jest waits for test to finish we need to declare it as async and then await the call to actions.authenticate. Otherwise the test will finish before the expect assertion, and we will have an evergreen test - a test that can never fail.

Running the above test gives us the following failure message:

  1. FAIL tests/unit/actions.spec.js
  2. authenticate authenticated a user
  3. SyntaxError: The string did not match the expected pattern.
  4. at XMLHttpRequest.open (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:482:15)
  5. at dispatchXhrRequest (node_modules/axios/lib/adapters/xhr.js:45:13)
  6. at xhrAdapter (node_modules/axios/lib/adapters/xhr.js:12:10)
  7. at dispatchRequest (node_modules/axios/lib/core/dispatchRequest.js:59:10)

This error is coming somewhere from within axios. We are making a request to /api..., and since we are running in a test environment, there isn’t even a server to make a request to, thus the error. We also did not defined url or body - we will do that while we solve the axios error.

Since we are using Jest, we can easily mock the API call using jest.mock. We will use a mock axios instead of the real one, which will give us more control over its behavior. Jest provides ES6 Class MocksVuex - Actions - 图4, which are a perfect fit for mocking axios.

The axios mock looks like this:

  1. let url = ''
  2. let body = {}
  3. jest.mock("axios", () => ({
  4. post: (_url, _body) => {
  5. return new Promise((resolve) => {
  6. url = _url
  7. body = _body
  8. resolve(true)
  9. })
  10. }
  11. }))

We save url and body to variables to we can assert the correct endpoint is receiving the correct payload. Since we don’t actually want to hit a real endpoint, we resolve the promise immediately which simulates a successful API call.

yarn unit:pass now yields a passing test!

Testing for the API Error

We only tested the case where the API call succeed. It’s important to test all the possible outcomes. Let’s write a test for the case where an error occurs. This time, we will write the test first, followed by the implementation.

The test can be written like this:

  1. it("catches an error", async () => {
  2. mockError = true
  3. await expect(actions.authenticate({ commit: jest.fn() }, {}))
  4. .rejects.toThrow("API Error occurred.")
  5. })

We need to find a way to force the axios mock to throw an error. That’s what the mockError variable is for. Update the axios mock like this:

  1. let url = ''
  2. let body = {}
  3. let mockError = false
  4. jest.mock("axios", () => ({
  5. post: (_url, _body) => {
  6. return new Promise((resolve) => {
  7. if (mockError)
  8. throw Error()
  9. url = _url
  10. body = _body
  11. resolve(true)
  12. })
  13. }
  14. }))

Jest will only allow accessing an out of scope variable in an ES6 class mock if the variable name is prepended with mock. Now we can simply do mockError = true and axios will throw an error.

Running this test gives us this failing error:

  1. FAIL tests/unit/actions.spec.js
  2. authenticate catchs an error
  3. expect(function).toThrow(string)
  4. Expected the function to throw an error matching:
  5. "API Error occurred."
  6. Instead, it threw:
  7. Mock error

It successfully caught the an error… but not the one we expected. Update authenticate to throw the error the test is expecting:

  1. export default {
  2. async authenticate({ commit }, { username, password }) {
  3. try {
  4. const authenticated = await axios.post("/api/authenticate", {
  5. username, password
  6. })
  7. commit("SET_AUTHENTICATED", authenticated)
  8. } catch (e) {
  9. throw Error("API Error occurred.")
  10. }
  11. }
  12. }

Now the test is passing.

Improvements

Now you know how to test actions in isolation. There is at least one potential improvement that can be made, which is to implement the axios mock as a manual mockVuex - Actions - 图5. This involves creating a __mocks__ directory on the same level as node_modules and implementing the mock module there. By doing this, you can share the mock implementation across all your tests. Jest will automatically use a __mocks__ mock implementation. There are plenty of examples on the Jest website and around the internet on how to do so. Refactoring this test to use a manual mock is left as an exercise to the reader.

Conclusion

This guide discussed:

  • using Jest ES6 class mocks
  • testing both the success and failure cases of an action

The source code for the test described on this page can be found hereVuex - Actions - 图6.