Search code examples
typescriptecmascript-6mockingaxiosaxios-mock-adapter

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


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;

Solution

  • 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();