Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 511
rtorres Avatar asked Feb 10 '18 16:02

rtorres


People also ask

Does Jest run tests sequentially?

Per file, it will run all describe blocks first and then run tests in sequence, in the order it encountered them while executing the describe blocks. If you want to run files in sequence as well, run Jest with the --runInBand command line flag.

What is before each in Jest?

beforeEach(fn, timeout) ​ Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting.

Does Jest cleanup after each test?

It will be executed before every test suite (every test file). Because test runner is already initialised, global functions like beforeAll and afterAll are in the scope just like in your regular test file so you can call them as you like.

Does beforeEach run before describe?

If beforeEach is inside a describe block, it runs for each test in the describe block. Using the same example where we have a database with test data, if your tests do not need the test data reset for each test, you can use beforeAll to run some code once, before any tests run.


1 Answers

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(() => {    ... }); 
like image 157
zzz Avatar answered Sep 22 '22 15:09

zzz