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.
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.
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 // ...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With