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
Answer
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