While tests run in source order, surrounding code does not which can lead to hard to debug issues.
Compare the test file below with the sample output below that and note the order of the log messages.
- Any code not inside of
it
,beforeAll
,afterAll
,beforeEach
orafterEach
runs immediately on initialisation.- This means code at the end of your file runs before even your before hooks.
- Code inside a
describe
block runs even if the block or file has no active tests.
*All
hooks wrap*Each
hooks, i.e.- For a given test all
beforeAll
hooks will have run before the firstbeforeEach
hook runs, regardless of the order in which they are defined and nested. - Similarly
afterAll
hooks run after allafterEach
hooks.
- For a given test all
If you want to try this yourself:
- Install Jest
npm i -g jest
- Save
runOrder.test.js
in a folder (ensure it is named with.test.js
as a suffix) - Run
jest
in that folder
async version of above, fwiw: https://gist.github.com/chuckplantain/8359063a1c025b5ccfce52b4f5707368