最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 15

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();
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论