7

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?

4
  • What is your state in the example? Commented Apr 9, 2022 at 14:14
  • The variable called theAnswer? Commented Apr 9, 2022 at 14:58
  • It looks like a constant, its value will not be changed in the test :-?. Commented Apr 9, 2022 at 15:02
  • A state doesn't have to be mutable, does it? :P Commented Apr 9, 2022 at 15:10

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.