Categories
JavaScript Answers

How to test axios in Jest?

Spread the love

Sometimes, we want to test axios in Jest.

In this article, we’ll look at how to test axios in Jest.

How to test axios in Jest?

To test axios in Jest, we can mock the axios dependency.

For instance, we write

import * as axios from "axios";

jest.mock("axios");

// ...

test("good response", () => {
  axios.get.mockImplementation(() => Promise.resolve({
    data: {
      //...
    }
  }));
  // ...
});

test("bad response", () => {
  axios.get.mockImplementation(() => Promise.reject({
    ...
  }));
  // ...
});

to call axios.get.mockImplementation to mock the implementation of the axios.get method with a function that returns a promise, which we passed in as the argument of mockImplementation.

We also called jest.mock("axios"); to mock the whole axios module.

Conclusion

To test axios in Jest, we can mock the axios dependency.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *