Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest run async function ONCE before all tests

I want to use jest for my server unit testing (instead of mocha+chai). Is there a way I can run async function before all tests start (init purposes) only once and not for every test file? And also if there's a way of running something after all tests are done?

like image 855
Roy Avatar asked Jul 26 '17 00:07

Roy


People also ask

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 // ...

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.

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.

How do you wait in Jest test?

Jest will wait until the done callback is called before finishing the test. fetchData(callback); }); If done() is never called, the test will fail (with timeout error), which is what you want to happen.


1 Answers

This feature was added in Jest's 22 version, with globalSetup and globalTeardown configurations. Look at this for examples.

package.json (or in jest.config.js)

{   ...   "jest": {     "globalSetup": "./scripts/jestGlobalSetup.js"   } } 

/scripts/jestGlobalSetup.js

module.exports = async () => {   console.log('\nhello, this is just before tests start running'); }; 

OR

export default async () => {   console.log('\nhello, this is just before tests start running'); }; 
like image 117
Amaury Liet Avatar answered Sep 20 '22 13:09

Amaury Liet