globalSetup
Path to a module that exports an async function that will run once before everything. Globals defined here can only be read in globalTeardown.
Typically it makes more sense to mock out any dependencies, but if you have no other choice than to spin up a database or other external service that absolutely must be running during the tests, globalSetup would be the place to do it.
setupFiles / setupFilesAfterEnv
setupFiles is a list of modules that will be run once before each test file and before the testing framework is installed.
setupFilesAfterEnv is a list of modules that will be run once before each test file but after the testing framework is installed in the environment.
Usually setupFilesAfterEnv is the right place for any setup code that should run before each test file. Only use setupFiles if you have a specific reason for needing the code to run before the testing framework is installed.
You can think of setupFilesAfterEnv as a global beforeAll.
If something must be done at the beginning of every test file (for example: configuring the Enzyme adapter), it makes sense to do it once in a setupFilesAfterEnv file.
beforeAll
Jest will run all beforeAll functions in a test file once before running anything else.
Use beforeAll for code that must run once at the beginning of one specific test file.
Example
package.json
{
...
"jest": {
"globalSetup": "./globalSetup.js",
"globalTeardown": "./globalTeardown.js",
"setupFiles": ["./setupFile.js"],
"setupFilesAfterEnv": ["./setupFileAfterEnv.js"]
}
}
globalSetup.js
module.exports = async () => {
console.log('in globalSetup');
global.GLOBALSETUP = 'globalSetup';
};
globalTeardown.js
module.exports = async () => {
console.log('in globalTeardown');
console.log(global.GLOBALSETUP);
};
setupFile.js
console.log('in setupFile');
global.order = [];
global.order.push(1);
setupFileAfterEnv.js
console.log('in setupFileAfterEnv');
global.order.push(2);
test.js
beforeAll(() => {
console.log('in beforeAll');
global.order.push(3);
});
test('order', () => {
expect(global.GLOBALSETUP).toBeUndefined(); // SUCCESS
expect(global.order).toEqual([1, 2, 3]); // SUCCESS
});
Output
Determining test suites to run...in globalSetup
console.log
in setupFile
at Object.<anonymous> (setupFile.js:1:98)
console.log
in setupFileAfterEnv
at Object.<anonymous> (setupFileAfterEnv.js:1:1)
console.log
in beforeAll
at Object.<anonymous>.beforeAll (src/test.js:3:11)
PASS src/test.js
✓ order (4 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.658 s, estimated 1 s
Ran all test suites.
in globalTeardown
globalSetup
Watch Usage: Press w to show more.