Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

631
Views
Testing axios.create() instance with jest

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
>;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

this works too and is more simple for your purpose

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

let apiSpy;
describe("getPokemonOptions", () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });
  it("Axios instance standart test", async () => {
    apiSpy = jest.spyOn(axiosInstance, "post");
    apiSpy.mockResolvedValue({});
    await axiosInstanceCounter();
    expect(axiosInstance).toBeCalledTimes(1);
  });
});
about 4 years ago · Juan Pablo Isaza Report

0

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" });
    });
  });
});

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!