简体   繁体   English

在Jest中,定义全局变量是否与在BeforeAll中定义它们相同?

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

When writing unit tests with Jest . Jest编写单元测试时。 Why would you use beforeAll over simply assigning value straight to global variables or vice versa? 你为什么要使用beforeAll而不是简单地将值直接赋给全局变量,反之亦然?

For example, what's the difference between the following two snippets? 例如,以下两个片段之间的区别是什么?

Snippet 1 片段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 片段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
  });
});

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. 但是,有些情况下使用beforeAll是有意义的 :如果你有异步代码,那么返回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. 如果从beforeAll回调中返回一个promise,则可以在测试中测试promise最终解析的值。

Quoting from the Jest documentation : 引用Jest文档

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. Jest提供beforeAll和afterAll来处理这种情况。 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: 例如,如果initializeCityDatabaseclearCityDatabase都返回了promises,并且city数据库可以在测试之间重用,我们可以将测试代码更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM