Why can't nested describe() blocks see vars defined in outer blocks?

The body of a describe block is executed before the beforeEach blocks.

This is exactly as expected. The problem is that your var trees variable is trying to access orchard before it has been initialized. The body of a describe block is executed before the beforeEach blocks. To solve this problem, the third code snippet is the only way to go.

Jasmine will first execute the describe blocks, and then execute the beforeEach blocks before running each test.


Well you could still initialize variables outside the beforeEach block. I generally do it for constants and still remain DRY without introducing beforeEach blocks.

describe('simple object', function () {
    const orchard = {
        trees: {
            apple: 10,
            orange: 20
        },
        bushes: {
            boysenberry: 40,
            blueberry: 35
        }
    };


    describe('trees', function () {
        const trees = orchard.trees;

        it('should have apples and oranges', function () {


            expect(trees.apple).toBeDefined();
            expect(trees.orange).toBeDefined();

            expect(trees.apple).toEqual(10);
            expect(trees.orange).toEqual(20);
        });
        it('should NOT have pears or cherries', function () {
            var trees = orchard.trees;

            expect(trees.pear).toBeUndefined();
            expect(trees.cherry).toBeUndefined();
        });
    });
});