Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest Mock User Module in All Test Files

Is there a way to make it so that jest always mocks my modules so I don't need to include it in all my jest tests?

Currently I have a config file

// src/__mocks__/config.js 
export default {
  dbConfig: 'TestDBConfiguration'
};

// src/config.js
export default {
  dbConfig: ... // Some other stuff
};

To run my unit tests I have to use the mocked config.js. Currently in all my unit tests I have to include jest.mock('../config');

// org.test.js
jest.mock('../../config');
import db from '../db';              // This internally uses the config file
import otherFile from '../otherFile'; // This also uses the config file

// Code that calls both db/otherFile

Sometimes when I create a test I might forget to include jest.mock('../config') which is one of the reasons why I want it included in all my tests.

I've looked into enabling automock but it seems to break my tests instead. https://facebook.github.io/jest/docs/en/configuration.html#automock-boolean

like image 226
Kenneth Truong Avatar asked Apr 06 '18 04:04

Kenneth Truong


2 Answers

You can add setupFiles or setupFilesAfterEnv into your jest configuration to run before all your tests.

https://jestjs.io/docs/configuration#setupfiles-array

// package.json
...
"jest": {
  "setupFiles": "./src/setupTests.js"
}

// setupTests.js
jest.mock('config'); // Path to config file
like image 198
smirky Avatar answered Nov 07 '22 05:11

smirky


Jest documentation has been updated and uses setupFilesAfterEnv to run code that can utilize Jest functions like jest.mock().

Updating @smirky's example to use setupFilesAfterEnv:

// package.json
...
"jest": {
  "setupFilesAfterEnv": ["./src/setupTests.js"]
}
// setupTests.js
jest.mock('config'); // Path to config file

On a sidenote, if you wish to import/require modules for every test you run, you can use setupFiles.

like image 29
Eduardo Portet Avatar answered Nov 07 '22 06:11

Eduardo Portet