Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React. how to mock api call NOT IN TESTS

E.g. I have a problem when some endpoints are down or causing errors, but I still need to develop. I have something like UserService.getUsers I am aware of mocking functions in jest and so on, but I have no idea how I'd better get fake data which I can specify myself.

I thought about a HOC, which redefines functions I need to mock like

UserService.getUsers=Promise.resolve({});

But I don't think this is the best way to do this

NOTE: That's not related to testing stuff

like image 777
fake822 Avatar asked Sep 15 '25 06:09

fake822


1 Answers

If you're using Webpack, you could use the resolve property of the Webpack configuration to alias your imports to some local mocked version.

https://webpack.js.org/configuration/resolve/

For example, if you had some import like this:

import UserService from 'some-package-or-path';

const myData = UserService.getUsers();

You can alias some-package-or-path to a local file:

// webpack.config.js
const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
     'some-package-or-path': path.resolve(__dirname, 'src/mocks/userServiceMock'),
    },
  },
};

// userServiceMock index.js
const mock = {
  getUserData: () => {
    return {
      mockedDataProperties: 'whatever'
    }
  }
};

export default mock;

Obviously your implementation will differ a bit but that's the gist of it.

like image 126
jered Avatar answered Sep 16 '25 20:09

jered