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
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With