开玩笑:将变量直接放在 describe-block 与 beforeAll 中

Jest: putting variable directly in describe-block vs. beforeAll

我知道在测试之间共享状态是不好的做法,应该尽可能避免。但我只是好奇下面这两个结构在 Jest 中有何不同:

描述块

describe('test suite', () => {
  const theAnswer = 42;

  test('a test case', () => {
    expect(theAnswer + 1).toEqual(43);
  });

  test('another test case', () => {
    expect(theAnswer + -1).toEqual(41);
  });
});

对比

beforeAll

describe('test suite with beforeAll', () => {
  let theAnswer;
  beforeAll(() => {
    theAnswer = 42;
  });

  test('a test case', () => {
    expect(theAnswer + 1).toEqual(43);
  });

  test('another test case', () => {
    expect(theAnswer + -1).toEqual(41);
  });
});

如果我们可以在describe块中直接声明共享variable/state,那么使用beforeAll有什么意义?

来自文档 One-Time Setup:

This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides beforeAll and afterAll to handle this situation.

如果设置像您一样是同步的,那么在 describe 块中声明变量就可以了。

If setup was synchronous, you could do this without beforeAll. The key is that Jest will wait for a promise to resolve, so you can have asynchronous setup as well.

但如果设置是异步的,则不能在 describe 块内进行。您必须在 before*after* 钩子中进行。

例如

describe('test suite', () => {
  let theAnswer;
  beforeAll((done) => {
    setTimeout(() => {
      theAnswer = 42;
      done();
    }, 1_000);
  });

  test('a test case', () => {
    expect(theAnswer + 1).toEqual(43);
  });

  test('another test case', () => {
    expect(theAnswer + -1).toEqual(41);
  });
});

Jest 会在 运行 测试用例之前等待设置完成。

查看有关 beforeAll

的文档