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
});
});
beforeAll(fn) #Runs a function before any of the tests in this file run. If the function returns a promise, Jest waits for that promise to resolve before running tests. This is often useful if you want to set up some global state that will be used by many tests.
Global Variables − A global variable has a global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
The keyword 'Global' is also used to create or declare a global variable inside a function. Usually, when you create a variable inside a function (a local variable), it can only be used within that function.
In 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();
});
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