axios-mock-adapter
axios-mock-adapter copied to clipboard
Switch between mock and real API
I have a config file that tells me whether API should use mock or not. Based on the configuration it should switch between Axios or Axios mock.
const MOCK_CONFIG = {
// set it to true to take mock API
API1: true,
API2: false,
};
I have a middleware file which does the condition check
const mock = new MockAdapter(axios);
function middleware(apiName) {
const mockData = (mock) => {
mock.onGet('/api1').reply(200, {
id: 1,
title: 'A Meeting',
});
mock.onGet('/api2').reply(200, {
sample: 1,
titleName: 'A Meeting',
});
}
if (MOCK_CONFIG[apiName]) {
mockData(mock); //setting handler
return () => {
mock.reset();
};
} else {
mock.restore();
}
}
return middleware;
Middleware function is called before axios.get() with the api name.
useEffect(() => {
async function fetchData1() {
middleware("API1");
try {
const response = await axios.get("/api1");
const data = await response.data;
} catch (error) {
throw error;
}
}
async function fetchData2() {
apiType2("API2");
try {
const response = await axios.get("/api2");
const data = await response.data;
} catch (error) {
throw error;
}
}
fetchData1();
fetchData2();
});
I'm getting "Request failed with status code 404" error for /api2.
agree with you, also want to know how to toggle the mock
From what I saw in the docs, it intercepts all requests... it is even possible to mock only the requests for which we have a mock code written?
I solved this in a similar way mentioned here: https://github.com/ctimmerm/axios-mock-adapter/issues/43
My implementation runs in a Vue 3 vuex mutation so I can toggle it via a UI switch.
My axios.js initilization file
const mock = new MockAdapter(axiosInstance);
const savedMockAdapter = axiosInstance.defaults.adapter
axiosInstance.defaults.adapter = `mock.originalAdapter;
export {
axiosInstance as axios,
mock as mock,
savedMockAdapter as savedMockAdapter,
}
Vuex Store:
import { axios, mock, savedMockAdapter } from '../../plugins/axios'
/*
* Toggle Mocking API on/off depending on boolean value of toggleState
*/
toggleMockApi(state, toggleState) {
if (toggleState === true) {
axios.defaults.adapter = savedMockAdapter;
state.mockApi = true;
} else {
axios.defaults.adapter = mock.originalAdapter;
state.mockApi = false;
}
},