Reputation: 652
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;
Upvotes: 2
Views: 4721
Reputation: 1401
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);
Upvotes: 1
Reputation: 222855
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();
Upvotes: 8