Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *