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

I tried many solution from this task. I want testing axios instance api call without any libralies (jes

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745647966a4638084.html

相关推荐

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

    I tried many solution from this task. I want testing axios instance api call without any libralies (jes

    22天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信