0

Axios instance creation in default.js file.

import axios from "axios";

const BASE_URL = import.meta.env.VITE_BACKEND_BASE_URL;

const instance = axios.create({
  baseURL: BASE_URL,
});

instance.defaults.headers.common["Accept"] = "application/json";
instance.defaults.headers.post["Content-Type"] = "application/json";

instance.interceptors.request.use(
  function (config) {
    config.headers.Authorization = localStorage.getItem("token");
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

export default instance;

I am writing unit test case using axios-mock-adapter library in default.test.js file as below.

import MockAdapter from "axios-mock-adapter";
import axios from "@/axios/default";

describe("Axios functions", () => {
  // Create a new instance of the mock adapter
  let mock;

  beforeEach(() => {
    mock = new MockAdapter(axios);
  });

  it("sends a GET request to the endpoint", async () => {
    const endpoint = "/example";
    const url = import.meta.env.VITE_BACKEND_BASE_URL + endpoint;
    const token = "12345";
    const expectedData = { example: "data" };

    // Mock the GET request to return the expected data
    mock
      .onGet(url, {
        headers: { Authorization: token, Accept: "application/json" },
      })
      .reply(200, expectedData);
    localStorage.setItem("token", token);

    // Call the get function and wait for it to resolve
    const response = await axios.get(endpoint);

    // Check that the GET request was called with the correct URL and headers
    expect(mock.history.get.length).toBe(1);
    expect(mock.history.get[0].url).toBe(endpoint);
    expect(mock.history.get[0].headers.Authorization).toBe(token);
    expect(mock.history.get[0].headers.Accept).toBe("application/json");

    // Check that the get function returns the expected data
    expect(response.data).toEqual(expectedData);
  });

  it("sends a POST request to the endpoint", async () => {
    const endpoint = "/example";
    const url = import.meta.env.VITE_BACKEND_BASE_URL + endpoint;
    const token = "12345";
    const postData = { example: "data" };
    const expectedData = { success: true };

    // Mock the POST request to return the expected data
    mock
      .onPost(url, postData, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      })
      .reply(200, expectedData);
    localStorage.setItem("token", token);

    // Call the post function and wait for it to resolve
    const response = await axios.post(endpoint, postData);

    // Check that the POST request was called with the correct URL, headers, and data
    expect(mock.history.post.length).toBe(1);
    expect(mock.history.post[0].url).toBe(endpoint);
    expect(mock.history.post[0].headers.Authorization).toBe(token);
    expect(mock.history.post[0].headers["Content-Type"]).toBe(
      "application/json"
    );
    expect(mock.history.post[0].headers.Accept).toBe("application/json");
    expect(JSON.parse(mock.history.post[0].data)).toEqual(postData);

    // Check that the post function returns the expected data
    expect(response.data).toEqual(expectedData);
  });
});

The unit test for get passes with no errors but for post gives Request failed with status code 404

PS - I am running these test using vitest as this is present in a vue app.

Suyash Mittal
  • 73
  • 1
  • 13

1 Answers1

0

It seems that you have defined the expected headers in your onPost interceptor, but the post request in your test is not sending the same headers over. This could be the reason why you're getting a 404 error.

To resolve this, make sure that the headers you pass in your post request match the headers you set in the onPost interceptor. You can pass the headers as an object in the third argument of the axios.post() method, like this:

    // Call the post function and wait for it to resolve
    const response = await axios.post(endpoint, postData, { headers }); 
Elias Amha
  • 349
  • 1
  • 5