Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest clean up after all tests have run

Is it possible in Jest to run cleanup or teardown tasks that run after all other tests have completed? Similar to how setupFiles allows one to set up tasks after before any test has run. Bonus points if this can also run regardless if the test had any errors.

Putting afterAll(() => {}) at the top level of a file (outside any describe function) appears only to run after tests from that particular file have finished.

The use case is I have many test files that will create users in a a development database, and I don't want to make each test file responsible for cleaning up and removing the user afterwards. Errors can also happen while writing tests, so if the cleanup happens regardless of errors that would be preferable.

like image 603
dcochran Avatar asked Dec 24 '16 18:12

dcochran


People also ask

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.

What is beforeAll and afterAll in Jest?

Jest provides beforeAll and afterAll . As with test / it it will wait for a promise to resolve, if the function returns a promise. beforeAll(() => { return new Promise(resolve => { // Asynchronous task // ...

What is Je beforeEach?

beforeEach(fn)Runs a function before each of the tests in this file runs. If the function returns a promise, Jest waits for that promise to resolve before running the test. This is often useful if you want to reset some global state that will be used by many tests.

Does Jest run describe sequentially?

Jest will execute different test files potentially in parallel, potentially in a different order from run to run. 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.


1 Answers

There's a sibling hook to setupFiles that will too fire before every test suite but right after your test runner (by default Jasmine2) has initialised global environment.

It's called setupFilesAfterEnv. Use it like this:

{     "setupFilesAfterEnv": ["<rootDir>/setup.js"] } 

Example setup.js:

beforeAll(() => console.log('beforeAll')); afterAll(() => console.log('afterAll')); 

setup.js doesn't need to export anything. 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.

setupTestFrameworkScriptFile firing beforeAll and afterAll

like image 130
Michał Pierzchała Avatar answered Sep 21 '22 15:09

Michał Pierzchała