How to clean up after all tests have run with Jest?

Sometimes, we want to clean up after all tests have run with Jest.

In this article, we’ll look at how to clean up after all tests have run with Jest.

How to clean up after all tests have run with Jest?

To clean up after all tests have run with Jest, we can add the setupFilesAfterEnv config property in our Jest config.

For instance, in package.json, we add

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

to run setupTests.js before each test.

Then in setupTests.js, we add

global.beforeEach(() => {
  //...
});

global.afterEach(() => {
  //...
});

to run the beforeEach hook before each test and afterEach hook after each test.

Conclusion

To clean up after all tests have run with Jest, we can add the setupFilesAfterEnv config property in our Jest config.