axios-mock-adapter如果我模拟请求,那么只能处理我模拟的请求

时间:2018-05-09 03:31:08

标签: typescript ecmascript-6 mocking axios axios-mock-adapter

我正在尝试模拟尚未在服务器上实现的API。但是,如果我模拟请求,那么只能处理我嘲笑的请求。如果我在mock.restore();之后添加mock.onGet,那么真正的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;

2 个答案:

答案 0 :(得分:1)

正如library documentation所解释的那样,应明确允许未被禁止的请求:

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

答案 1 :(得分:0)

添加到@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);