Home > database >  Execution of code in other describe blocks - jest
Execution of code in other describe blocks - jest

Time:02-22

I have the following test setup:

describe(`my tests`, () => {
    describe(`Should not run`, () => {
        console.log(`Should not be printed`);
        describe(`Should also not run`, () => {
            console.log(`Should also not be printed`);
            test(`Then an exception is thrown`, () => {
                console.log(`Should definitely not be printed`);
                throw new Error(`whoops`);
            })
        })

        describe(`Should run`, () => {
            console.log(`Should run`)
            test(`Then I should get this list in the format I expect`, () => {
                console.log(`Should definitely be printed`);
            })
        })

        describe(`Should not run`, () => {
            console.log(`Should not be printed`);
            test(`Then I should get an empty list`, () => {
                throw new Error(`whoops`);
            })
        })
    })
})

When I ask IntelliJ to only run the test case test('Then I should get this list in the format I expect'), I still get the following output:

> Should not be printed
> Should also not be printed
> Should run
> Should not be printed
> Should definitely be printed

Howcome the code of the other describe blocks is being executed? I thought the describe block allowed you to scope test setup so that it only runs for the tests inside that specific block.

CodePudding user response:

Seems that this is the standard and documented behaviour:

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 inside before* and after* handlers rather than inside 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.

  • Related