Can someone explain simply what the practical difference is in how each of the following tests is executed:
Case 1
const variable = generateVariable();
test('generates the correct value', () => {
expect(variable).toBe('desired-value');
});
Case 2
test('generates the correct value', () => {
const variable = generateVariable();
expect(variable).toBe('desired-value');
});
Case 3
describe('Variable generator', () => {
beforeEach(() => {
const variable = generateVariable();
});
test('generates the correct value', () => {
expect(variable).toBe('desired-value');
});
});
Case 4
describe('Variable generator', () => {
beforeAll(() => {
const variable = generateVariable();
});
test('generates the correct value', () => {
expect(variable).toBe('desired-value');
});
});
Case 1
Case 2
Case 3
Case 4
In case 1, variable will be available to all tests. Ideally, this should be something that it's not mutated in tests, otherwise tests might randomly fail.
Case 2 is the best way if you want to keep variable in isolation. Its binding is only valid within the test body. Other occurrences of variable can be declared in other tests.
In case 3 and 4, you won't be able to use variable in the test, as it's declared and initialized within a different function body (beforeEach or beforeAll). As Seti mentioned in the previous answer, you'll get an error when trying to use variable.
There's a subtle difference to overcome this issue:
let variable;
describe('Variable generator', () => {
beforeEach(() => {
variable = generateVariable();
});
test('generates the correct value', () => {
expect(variable).toBe('desired-value');
});
});
In this case, variable can be used in all the tests, and it will be initialized before each test. It's a common practice if you want to initialize something the same way in many tests.