Home > Net >  Testing axios.create() instance with jest
Testing axios.create() instance with jest

Time:02-20

I tried many solution from this task. I want testing axios instance api call without any libralies (jest-axios-mock, moaxios, msw, etc). I hope it's possible, because i succeeded testing simple axios call ( axios.get / axios.post without .create ) The main problem comes i tried testing axios instance call, i collides with three main errors on different attempts.

1 axios_instance_1.axiosInstance is not a function

2 Cannot read property 'then' of undefined

3 Cannot read property 'post' of undefined

I get this when i try bypassing module mock ( jestjs.io/docs/bypassing-module-mocks )

My last attempt looked like this

axios-instance.ts

import axios from "axios";
export const axiosInstance = axios.create({
    headers: {'X-Custom-Header': 'foobar'}
})

api.ts

import { axiosInstance } from "../instancec/axios-instance";
export const axiosInstanceCounter = () => {
  return axiosInstance({
    method: 'post'
  }).then((data) => {
    console.log(data)
  })
}

axios.test.ts

import { axiosInstanceCounter } from '../features/api/axiosTest';
import { axiosInstance } from '../features/instancec/axios-instance';
import axios, { AxiosResponse } from 'axios';

jest.mock('../features/instancec/axios-instance', () => ({
   const instance = {
     create: jest.fn(),
   };
   return jest.fn(() => instance);
}));

it('Axios instance standart test', async () => {
    (axiosInstance.post as jest.Mock).mockResolvedValueOnce(() =>
      Promise.resolve(),
    );
    await axiosInstanceCounter();
    expect(axiosInstance).toBeCalledTimes(1);
});

And last error i receive it is Cannot read 'post' of undefined. Create mocks file in folder mocks and export from there also doesn't help. I don't quite understand why it happens and I'll be very thankful any hint, i also tried option with jest.spyOn but this failed.

Addition to solution

I replace mocked() with ts-jest to avoid warnings

const mockedAxiosInstance = axiosInstance as jest.MockedFunction<
  typeof axiosInstance
>;

CodePudding user response:

As you can see, return axiosInstance({ means axiosInstance is a function, then if you want to test axiosInstanceCounter function, just mock axiosInstance as a normal function(in your case the api call will not return anything):

api.test.ts // testing for api.ts

import { AxiosPromise } from "axios";
import { mocked } from "ts-jest/utils"; // a helper function from ts-jest
import { axiosInstanceCounter } from '../features/api/axiosTest'; // should be ../features/api ???
import { axiosInstance } from '../features/instancec/axios-instance';

jest.mock("../features/instancec/axios-instance");

describe("api", () => {
  describe("axiosInstanceCounter()", () => {
    it("should call api with correct parameters", async () => {
      // mock to resolve a Promise<void>
      mocked(axiosInstance).mockResolvedValue(Promise.resolve() as unknown as AxiosPromise<void>);

      await axiosInstanceCounter();

      expect(axiosInstance).toHaveBeenCalledWith({ method: "post" });
    });
  });
});

  • Related