How to run global test setup before each test in Jest?

Sometimes, we want to run global test setup before each test in Jest.

In this article, we’ll look at how to run global test setup before each test in Jest.

How to run global test setup before each test in Jest?

To run global test setup before each test in 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 run global test setup before each test in Jest, we can add the setupFilesAfterEnv config property in our Jest config.