From 4eded0c1b7e2c18411000c3396585bf1b41c21b0 Mon Sep 17 00:00:00 2001 From: David Park Date: Wed, 3 Jan 2018 11:11:44 +0000 Subject: [PATCH] Improve documentation of `describe` and `test` ordering. (#5217) * Improve notes on execution order of test file code Explain that describe blocks are executed first (I've had annoying things where describes were being used to set up state instead of before* hooks), note that tests are run serially in the order they are discovered, and add a note about `test.concurrent`. * Clarify tests are run serially and tidy up. * Improve example. * Update CHANGELOG.md * Remove test.concurrent documentation Also fix typo! --- CHANGELOG.md | 3 +++ docs/SetupAndTeardown.md | 47 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98f6d7991b28..6ccf2a54bc09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ ### Chore & Maintenance +* `[docs]` Describe the order of execution of describe and test blocks, and a note on using `test.concurrent`. + ([#5217](https://github.com/facebook/jest/pull/5217)) + ## jest 22.0.4 ### Fixes diff --git a/docs/SetupAndTeardown.md b/docs/SetupAndTeardown.md index 8f566dcbb479..e4dbe65352d4 100644 --- a/docs/SetupAndTeardown.md +++ b/docs/SetupAndTeardown.md @@ -147,6 +147,53 @@ describe('Scoped / Nested block', () => { // 1 - afterAll ``` +### Order of execution of describe and test blocks + +Jest executes all describe handlers in a test file *before* it executes any of the actual tests. This is another reason to do setup and teardown in `before*` and `after*` handlers rather in the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on. + +Consider the following illustrative test file and output: + +``` +describe('outer', () => { + + console.log(`describe outer-a`); + + describe('describe inner 1', () => { + console.log(`describe inner 1`); + test('test 1', () => { + console.log(`test for describe inner 1`); + expect(true).toEqual(true); + }); + }); + + console.log(`describe outer-b`); + + test('test 1', () => { + console.log(`test for describe outer`); + expect(true).toEqual(true); + }); + + describe('describe inner 2', () => { + console.log(`describe inner 2`); + test('test for describe inner 2', () => { + console.log(`test for describe inner 2`); + expect(false).toEqual(false); + }) + }); + + console.log(`describe outer-c`); +}); + +// describe outer-a +// describe inner 1 +// describe outer-b +// describe inner 2 +// describe outer-c +// test for describe inner 1 +// test for describe outer +// test for describe inner 2 +``` + ### General Advice If a test is failing, one of the first things to check should be whether the