rtorres
rtorres

Reputation: 2951

Running a global test setup before each test in Jest

I'm trying to have a test setup function executed before each single test in my Jest test suite. I know that I can use beforeEach to accomplish this within a single test file, but I want to do it globally for all my test files without having to explicitly modify each single file.

I looked into the jest configuration file, and noticed a couple of configs that thought could have worked: globalSetup and setupFiles, but they seem to be run only once (at the very beginning of the test run). Like I said, I need it to be run before "each" it block in my test files.

Is this possible?

Upvotes: 67

Views: 41407

Answers (3)

zzz
zzz

Reputation: 1105

You could use setupFilesAfterEnv (which replaces setupTestFrameworkScriptFile, deprecated from jest version 24.x) which will run before each test

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

And in setupTests.js, you can directly write:

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

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

Upvotes: 81

David De Anda
David De Anda

Reputation: 445

setupFilesAfterEnv configuration is the way to go, and yes you can use beforeEach in that file and it will run in every test across all the suit.

// jest.config.js

module.exports = {
  setupFilesAfterEnv: ['<rootDir>/tests/setupTests.ts']
}

// tests/setupTests.ts

beforeEach(() => {
  console.log('before each')
})

afterEach(() => {
  console.log('after each')
})

Try it out!

Upvotes: 17

Alvin S. Lee
Alvin S. Lee

Reputation: 5182

Just as a follow-up to the answer from @zzz, the more recent documentation on Configuring Jest notes:

Note: setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv.

So now, your file should look like this:

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

Upvotes: 17

Related Questions