1

I'm trying to mock API that not implemented on server yet. But if I mock the requests then works only the requests that I mock. If I add mock.restore(); after mock.onGet then real API works fine, but then there is no mock API that I need too.

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;
Platon Efimov
  • 582
  • 2
  • 6
  • 25

2 Answers2

7

As library documentation explains, unmocked requests should be explicitly allowed:

// Mock specific requests, but let unmatched ones through
mock
  .onGet('/foo').reply(200)
  .onPut('/bar', { xyz: 'abc' }).reply(204)
  .onAny().passThrough();
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
1

Adding to @Estus answer, we can forward other requests to server as below as well.

// 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);
Ranga
  • 1,191
  • 12
  • 19