React Made Native Easy

  Edit

Mocking modules in Jest

Like other testing frameworks, Jest also supports mocking modules, both Node.js modules and custom JS modules.

Most of the React Native specific utilities are automatically mocked for us since we are using react-native preset. If you install any other modules which aren't automatically mocked, say a react-native module which has a dependency on NativeModules, you would need to mock the module manually.

How do you mock manually

While Jest supports a bunch of methods for mocking utilities, we suggest doing manual mocks by creating a file with the same filename inside a __mocks__ folder, adjacent to the module which we are mocking.

├── config
├── __mocks__
│   └── react-native-exception-handler.js
├── utils
│   ├── __mocks__
│   │   └── language.util.js
│   └── language.util.js
└── node_modules

As you can see above, you can mock both nodemodules and your custom defined JS files. Whenever you import utils/language.util file, Jest will automatically read it from `_mocks/language.util.js`.

If you would like to un-mock a file and read the real source code instead of mocking it, you could do that using jest.unmock('module_path') function in the test case.

Note: You can also use the automock feature of Jest by using a function called jest.genMockFromModule. But this might not work for some of the modules which return nested methods and it will only mock the functions which a module exports.

Example of automock:

Let's say you want to mock the functions exposed by a Node.js module called react-native-exception-handler

Since it is a nodemodule, we would need to put the mock file inside `_mocks/react-native-exception-handler`. Refer to the tree above to know where this file will lie.

To automock the module, our file would look something like this:

__mocks__/react-native-exception-handler.js

const mockedModule = jest.mock('react-native-exception-handler');

module.exports = mockedModule;

If we want to mock this module manually, we need to know all the functions the module exports and mock them individually. Our file would look something like this:

__mocks__/react-native-exception-handler.js

export default {
  setJSExceptionHandler: jest.fn(),
  getJSExceptionHandler: jest.fn(),
  setNativeExceptionHandler: jest.fn()
};

Then in the test file, we will say that we want to mock a module by doing:

jest.mock('module_path');

NPM modules inside the mock folder residing adjacent to the node_modules are mocked by default. Hence we do not need to mock them separately.

To know more about the manual mocking in Jest, please visit here.