ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.44k stars 244 forks source link

Switch between mock and real API #273

Open NethraRaghu opened 4 years ago

NethraRaghu commented 4 years ago

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.

httol commented 3 years ago

agree with you, also want to know how to toggle the mock

orosro commented 3 years ago

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?

timmaier commented 3 years ago

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;
    }
},