Home > Back-end >  Jest: putting variable directly in describe-block vs. beforeAll
Jest: putting variable directly in describe-block vs. beforeAll

Time:04-13

I know that having shared state between tests is bad practice and should be avoided if possible. But I'm just curious how are these two constructs below different in Jest:

describe-block

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

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

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

vs.

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

What's the significance of using beforeAll if we can directly declare a shared variable/state in the describe block?

CodePudding user response:

From the doc 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.

If the setup is synchronous like yours, declaring the variables in the describe block is OK.

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.

But if the setup is asynchronous, you can't do it inside describe block. You must do it in before* and after* hooks.

E.g.

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 will wait for the setup to be done before running the test cases.

See the doc about beforeAll

  • Related