Jest clean up after all tests have run

To do some tasks after all test suites finish, use globalTeardown. Example:

In package.json:

{
  "jest": {
    "globalTeardown": "<rootDir>/teardownJest.js"
  },
} 

In teardownJest.js:

const teardown = async () => {
  console.log('called after all test suites');
}

module.exports = teardown;

Keep in mind that jest imports every module from scratch for each test suit and teardown file. From official documentation:

By default, each test file gets its own independent module registry

So, you cannot share the same DB module's instance for each test suite or teardown file. Therefore, If you wanted to close db connection after all test suits, this method would not work


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:

  • I am using Jest 24.8
  • Reference: setupFilesAfterEnv

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