beforeAll(fn, timeout)
Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests.
Optionally, you can provide a timeout
(in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.
This is often useful if you want to set up some global state that will be used by many tests.
For example:
const globalDatabase = makeGlobalDatabase();
beforeAll(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});
// Since we only set up the database once in this example, it's important
// that our tests don't modify it.
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
Here the beforeAll
ensures that the database is set up before tests run. If setup was synchronous, you could do this without beforeAll
. The key is that Jest will wait for a promise to resolve, so you can have asynchronous setup as well.
If beforeAll
is inside a describe
block, it runs at the beginning of the describe block.
If you want to run something before every test instead of before any test runs, use beforeEach
instead.