Cant make axios-mock-adpter work properly

841 views Asked by At

I trying to implement the axios-mock-adpter just for mock (not unit test) while the backend do they work.

Im using Nextjs V.13,axios and axios-mock-adpter

1-AxiosMock and Mock Initializer

import axios from "axios";
import MockAdapter from "axios-mock-adapter";
export function createAxiosInstace() {
const axiosInstance = axios.create({
   baseURL: "http://localhost:3000",
 });
 return axiosInstance;
}

const mock = new MockAdapter(createAxiosInstace());
export default mock;

2-Make mock for a payment endpoint

import mock from "../axiosMock";

mock.onPost("/api/payments").reply(() => {
const paymentStatus = {
  id: "5e8891ab188cd28",
  status: "aproved",
  email: "[email protected]",
  name: "Jane Doe",
 };
 return [200, { paymentStatus }];
});

3-Using a function the way we(workspace) use

import { createAxiosInstace } from "@/lib/axiosMock";

export async function sendPayment() {
 const response = await createAxiosInstace()
.post("/api/payments")
.then((response) => {
  return response;
})
.catch((error) => {
  return error;
});
 return response;
}

4-Get 404 error :) Error Image

1

There are 1 answers

7
Paulo Fernando On BEST ANSWER

The way you are doing, you are creating a new axios instance everytime, you need to create one, apply the mock to it, and then use this same instance. Also you need to specify the routes or use mock.onAny for example:

https://codesandbox.io/s/old-microservice-4gxxl4?file=/lib/axios.js

mock.js

import MockAdapter from "axios-mock-adapter";

export default function applyMockAdapter(axiosInstance) {
    const mock = new MockAdapter(axiosInstance);

    mock.onPost('/api/payments').reply(200, {
        status: "api/payments OK! "
    })

    mock.onAny().reply(200, {
        status: "Any other call will get this ",
        moreData: [1, 3, 4, 5,]
    })
}

axios.js

import axios from "axios";
import applyMockAdapter from "./mock";

const axiosInstance = axios.create({
    baseURL: "http://localhost:3000",
});

const someConfigToUseMock = true;

if (someConfigToUseMock) {
    applyMockAdapter(axiosInstance);
}

export default axiosInstance;

page.js

"use client";
import axiosInstance from '@/lib/axios'; // different name to avoid wrong import

export default function Home() {
  async function sendPayment() {
    const response = await axiosInstance // different name to avoid wrong import
      .post("/api/payments")
      .then((response) => {
        return response;
      })
      .catch((error) => {
        return error;
      });
    return response;
  }

  return (
    <button onClick={() => {
      sendPayment().then(console.log);
    }} >Make Request</button>
  )
}

If you need to use a function you need the fuction to always return the same instance like this:

import axios from "axios";
import MockAdapter from "axios-mock-adapter";

const axiosInstance = axios.create({
    baseURL: "http://localhost:3000",
  });

export function createAxiosInstace() {
 return axiosInstance;
}

const mock = new MockAdapter(createAxiosInstace());
export default mock;