最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Testing axios.create() instance with jest - Stack Overflow

matteradmin5PV0评论

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 es 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
>;

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 es 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
>;
Share Improve this question edited Feb 20, 2022 at 15:11 Arthur asked Feb 20, 2022 at 9:47 ArthurArthur 351 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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

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

Post a comment

comment list (0)

  1. No comments so far