Mock Axios with Jest

Mock request made by Axios using Jest in Node.js. Unit tests more unit


Andres Canavesi
Jan 31, 2021
Mock Axios with Jest using successful and error response
featured image
Mock with a successful response
      
import axios from "axios";

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

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

      return Promise.resolve(myResponse);
    });
    mockedAxios.get.mockImplementation(mockGet);
      
    
Mock with an error response
      
import axios from "axios";

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

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

Photo by Green Chameleon on Unsplash

Recommended posts