Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Jest, Are Defining Global Variables the Same as if They are Defined in BeforeAll?

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
  });
});
like image 815
Shan Avatar asked Dec 20 '17 19:12

Shan


People also ask

What is Jest beforeAll?

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.

What is the difference between a global and a local variable in JS?

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.

Can you define a global variable in a 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.


1 Answers

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();
});
like image 69
Patrick Hund Avatar answered Oct 07 '22 13:10

Patrick Hund