axios-mock-adapter 如果我模拟请求然后只处理我模拟的请求

axios-mock-adapter If I mock the requests then works only the requests that I mock

我正在尝试模拟尚未在服务器上实现的 API。但是,如果我模拟请求,则只处理我模拟的请求。如果我在 mock.onGet 之后添加 mock.restore(); 那么真正的 API 工作正常,但是没有我也需要的模拟 API。

import * as axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mainConfig = require('../../../config/main.js');

const request = (axios as any).create({
  baseURL: mainConfig.apiBaseUrl,
  headers: {
    'Content-Type': 'application/json',
  },
});

const mock = new MockAdapter(request);

mock.onGet('basket').reply(200, {...});

export default request;

正如 library documentation 所解释的,未模拟的请求应该被明确允许:

// Mock specific requests, but let unmatched ones through
mock
  .onGet('/foo').reply(200)
  .onPut('/bar', { xyz: 'abc' }).reply(204)
  .onAny().passThrough();

添加到@Estus 答案,我们也可以将其他请求转发到服务器,如下所示。

// Mock all requests to /foo with HTTP 200, 
// but forward any others requests to server
var mock = new MockAdapter(axiosInstance, { onNoMatch: "passthrough" });

mock.onAny("/foo").reply(200);