When writing unit tests with Jest. Why would you use beforeAll over simply assigning value straight to global variables or vice versa?
For example, what's the difference between the following two snippets?
Snippet 1
const mock = { key1: 'val1', key2: 'val2' };
describe('Test Cases', () => {
test('Case 1', () => {
// tests that use mock variable
});
test('Case 2', () => {
// more tests that use mock variable
});
});
Snippet 2
const mock = {};
beforeAll(() => {
mock.key1 = 'val1';
mock.key2 = 'val2';
});
describe('Test Cases', () => {
test('Case 1', () => {
// tests that use mock variable
});
test('Case 2', () => {
// more tests that use mock variable
});
});
When writing unit tests with Jest. Why would you use beforeAll over simply assigning value straight to global variables or vice versa?
For example, what's the difference between the following two snippets?
Snippet 1
const mock = { key1: 'val1', key2: 'val2' };
describe('Test Cases', () => {
test('Case 1', () => {
// tests that use mock variable
});
test('Case 2', () => {
// more tests that use mock variable
});
});
Snippet 2
const mock = {};
beforeAll(() => {
mock.key1 = 'val1';
mock.key2 = 'val2';
});
describe('Test Cases', () => {
test('Case 1', () => {
// tests that use mock variable
});
test('Case 2', () => {
// more tests that use mock variable
});
});
Share
Improve this question
asked Dec 20, 2017 at 19:32
ShanShan
6046 silver badges12 bronze badges
1 Answer
Reset to default 15In your example, it does not make any difference. There are cases when it does make sense, however, to use beforeAll: if you have asynchronous code, functions that return promises.
If you return a promise from the beforeAll callback, you can test the value that the promise eventually resolves to easily in a test.
Quoting from the Jest documentation:
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't just do it inline. Jest provides beforeAll and afterAll to handle this situation. For example, if both initializeCityDatabase and clearCityDatabase returned promises, and the city database could be reused between tests, we could change our test code to:
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});