1

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: "jane@test.com",
  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

Willien
  • 25
  • 4

1 Answers1

1

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;
Paulo Fernando
  • 3,148
  • 3
  • 5
  • 21
  • Vlw pela resposta detalhada Porem continua dando 404 – Willien Jun 23 '23 at 18:00
  • Alguma chance de você ter errado alguma config? sandbox: https://codesandbox.io/s/old-microservice-4gxxl4?file=/lib/axios.js – Paulo Fernando Jun 23 '23 at 18:15
  • Se continuar 404 tenta fazer um sandbox com o erro – Paulo Fernando Jun 23 '23 at 18:16
  • Ta ai: https://codesandbox.io/p/sandbox/upbeat-panka-f8jvtm?file=%2F.codesandbox%2Ftasks.json%3A1%2C1 (Acho que estou deixando algo passar) – Willien Jun 23 '23 at 19:08
  • Vi o problema, eu coloquei o nome do custom axios de `axios` então fica fácil de importar o errado, eu troquei o nome: https://codesandbox.io/p/sandbox/awesome-allen-cjdp4h?file=%2Fapp%2FraffleCalls.js%3A8%2C7 – Paulo Fernando Jun 23 '23 at 19:22
  • Aproveitando o contato, como que você fez para importar as dependencias nesse sandbox? eu tentei dele primerro e Não achei de jeito nenhum – Paulo Fernando Jun 23 '23 at 19:23
  • Funcionou perfeitamente cara, vlw msm Sobre a segunda pergunta: Ue, ñ fiz nd de mais, so importei e deu certo kkkkk – Willien Jun 23 '23 at 19:38