Search code examples
reactjsaxiosrequestresponseinterceptor

how to mock data in react axios interceptor when backend is off?


I want to make fullstack app working only when frontend is working. I have prepared mocked json data, that i want to pass into request interceptor to create a Promise with those mocked data.

I tried to create an if statement in interceptor which looked at the api path and injected mocked data into.

import apiFriends from './mockedData/friends';

const zpiApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10 * 1000,
});

zpiApi.interceptors.request.use((request) => {
  const token = localStorage.getItem('token');
  if (token) {
    request.headers.Authorization = `Bearer ${token}`;
  }
  console.log(request);

  if (request.url?.includes('/friends/search/')) {
    return Promise.resolve({
      ...request,
      headers: request.headers,
      data: apiFriends,
      status: 200,
      statusText: 'OK',
    });
  }

  return request;
});

export default zpiApi;

But that looked like it still communicates with backend - it returns backend data instead of mocked.

Then i tried to remove ...request, but that removes whole config and i get such error:

Cannot read properties of undefined (reading 'toUpperCase')
TypeError: Cannot read properties of undefined (reading 'toUpperCase')
    at dispatchXhrRequest (http://localhost:3000/static/js/bundle.js:153139:32)
    at new Promise (<anonymous>)
    at xhr (http://localhost:3000/static/js/bundle.js:153109:10)
    at Axios.dispatchRequest (http://localhost:3000/static/js/bundle.js:154301:10)
    at async FriendsService.getUsersBySearchPhrase (http://localhost:3000/static/js/bundle.js:18664:25)

which means there is no config at all (from what i've read online).

So what i'm trying to do is for specific api calls to use mocked data instead of backend, but now i'm struggling to make it work even for single api call.

From what i've tried to find online, there are only questions about mocked data in jest.

Thanks in advance for everyone.


Solution

  • You can use a library called axios-mock-adapter to mock your data. It’s like pretending to make a request, but instead of going to the server, it uses your mock data.

    First, you need to install it. You can do this by running npm install axios-mock-adapter --save-dev in your terminal.

    Then, in your code, you can set up the mock like this:

    import axios from 'axios';
    import MockAdapter from 'axios-mock-adapter';
    
    // This sets the mock adapter on the default instance
    var mock = new MockAdapter(axios);
    
    // Mock any GET request to /friends/search/
    // arguments for reply are (status, data, headers)
    mock.onGet('/friends/search/').reply(200, apiFriends);
    
    

    Now, whenever you make a GET request to /friends/search/, it will return your apiFriends data instead of going to the server.