Jest clean up after all tests have run Jest clean up after all tests have run reactjs reactjs

Jest clean up after all tests have run


There's a sibling hook to setupFiles that will too fire before every test suite but right after your test runner (by default Jasmine2) has initialised global environment.

It's called setupFilesAfterEnv. Use it like this:

{    "setupFilesAfterEnv": ["<rootDir>/setup.js"]}

Example setup.js:

beforeAll(() => console.log('beforeAll'));afterAll(() => console.log('afterAll'));

setup.js doesn't need to export anything. It will be executed before every test suite (every test file). Because test runner is already initialised, global functions like beforeAll and afterAll are in the scope just like in your regular test file so you can call them as you like.

setupTestFrameworkScriptFile firing beforeAll and afterAll


In jest.config.js:

module.exports = {    // ...    setupFilesAfterEnv: [        "./test/setup.js",        // can have more setup files here    ],}

In ./test/setup.js:

afterAll(() => { // or: afterAll(async () => { }); to support await calls    // Cleanup logic});

Note:


There looks like there is a feature called a reporter that just does exactly this: