Mock Axios with Jest

Reading Time: < 1 minutes

Mock with a successful response

      
import axios from "axios";

jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios="">;

 const mockGet = jest.fn();
    mockGet.mockImplementation(() => {
      const myResponse = {
        status: 200,
        data: {
          data: [{ id: 1 }, { id: 2 }],
        },
      };

      return Promise.resolve(myResponse);
    });
    mockedAxios.get.mockImplementation(mockGet);
      </typeof>

Mock with an error response

      
import axios from "axios";

jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios="">;

const mockGet = jest.fn();
    mockGet.mockImplementation(() => {
      const error = {
        response: {
          status: 404,
        },
      };
      return Promise.reject(error);
    });
    mockedAxios.get.mockImplementation(mockGet);
      </typeof>

Photo by Green Chameleon on Unsplash


About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: