我try 实现axios-mock-adterter只是为了模拟(而不是单元测试),而后端是这样做的.

我正在使用Nextjs V.13、axios和axios-mock-adperter

1-AxiosMock和模拟初始化器

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-模拟支付终结点

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-以我们(工作空间)使用的方式使用函数

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-获取404错误:) Error Image

推荐答案

按照您所做的,您每次都会创建一个新的AXIOS实例,您需要创建一个实例,对其应用模拟,然后使用相同的实例.此外,您还需要指定路由或使用mock.onAny,例如:

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;

Reactjs相关问答推荐

CSS转换不适用于React MUI对象

如何使用json将购物车数组传递到后台API

在下一个js中使用ESTAccountWithEmailAndPassword函数时循环

如何使用Reaction Testing Library+Vitest正确更新单元测试中的输入?

react 挂钩-使用有效澄清

我如何在不被 destruct 的情况下将导航栏固定在顶部?

折叠并重新打开react 手风琴将重置内部状态

在继承值更改时重置react 挂钩窗体字段值

Antd V5组件自定义主题

onClick 事件处理程序未应用于样式组件

从 redux 调用UPDATE_DATA操作时状态变得未定义

无法通过react 路由中的链接传递信息

React Router 6 点击链接在 React 18 应用中打开 flickr 页面

React Router v6 路径中的符号

React 测试库 - 如何断言异步函数之间的中间状态?

useState 在生命周期中的位置

Cypress ,重试不再附加到 DOM 的元素

我在使用 Elements of stripe 时使用 React router v6

下拉菜单在 AppBar 中未正确对齐

点击提交后自动添加#