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
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.onAnyfor example:https://codesandbox.io/s/old-microservice-4gxxl4?file=/lib/axios.js
mock.js
axios.js
page.js
If you need to use a function you need the fuction to always return the same instance like this: