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?
41
votes
4 Answers
36
votes
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');
};
14
votes
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
// ...
resolve();
});
});
It also supports callback style, if you have some existing test code that uses callbacks, although it's recommended to use promises.
beforeAll(done => {
// Asynchronous task
// ...
done();
});
4
votes
jest provides options for both global setup and teardown in new versions. You can create files for both setup and teardown exporting an async function and provide that path in jest configurarion like this.
"globalSetup": "setup-file-path",
"globalTeardown": "tear-down-file-path"
You can read about it further here