Don P
Don P

Reputation: 63768

Jest - do something before every test

Jest provides some useful methods for executing something before your tests: beforeEach() and beforeAll(). Jest docs on setup

The issue with these is they can only be placed inside of a describe block. So if I have many files, each with their own describe block, I need to place to beforeEach() in every file.

How can I run some code before & after every test, while only adding it once (instead of adding it in every describe block)?

Upvotes: 2

Views: 4800

Answers (1)

PeterDanis
PeterDanis

Reputation: 9336

You can try the globalSetup Jest config key. It is an optional key and it can be used to run an async function once before all test suites.

Please see https://github.com/facebook/jest/blob/master/docs/Configuration.md#globalsetup-string

Example of setting up globalSetup in package.json:

  jest: {
    globalSetup: "./path-to-global-setup.js"
  }

... or in jest.config.js:

module.exports = {
  globalSetup: "./path-to-global-setup.js"
};

Example of global-setup.js file:

module.exports = async function() {
  // do something
};

This file will not be transformed by babel when you run your test suite.

Upvotes: 4

Related Questions