Jest: how to automock modules on all tests

You can use jest’s automock and unmockedModulePathPatterns to auto mock modules on all of your unit tests. But there is performance issue and it is a hassle to set up unmockedModulePathPatterns. A better alternative is to use jest’s setupTestFrameworkScriptFile and jest.mock.

Here is how to setup automock using setupTestFrameworkScriptFile :

  • webpack.config.js:
resolve: {
root: path.resolve(__dirname, 'src'),
...
}
  • package.json (jest config):
"jest": {
...
"setupTestFrameworkScriptFile": "<rootDir>/jest_setup",
"automock": false, // make sure automock is off. This is default
...
}
  • jest_setup.js (jest script):
// This script runs at the beginning of all of your unit tests
// Jest will use the mocked module whenever
// you import the modules defined in this file
// use modules inside __mock__ folder
jest.mock('your_module1');
// inline functions
jest.mock('your_module2', () => { // mock });
...

That’s all!!