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

前端 未结 3 1126
攒了一身酷
攒了一身酷 2021-01-30 20:07

I\'ve run into this issue in real code, but I put together a trivial example to prove the point.

The below code works fine. I\'ve set up a variable in my root desc

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 20:31

    Lets take the third code snippet. Further, it can be refactored as below:

    describe('simple object', function () {
        var orchard;
    
        beforeEach(function () {
            orchard = {
                trees: {
                    apple: 10,
                    orange : 20
                },
                bushes: {
                    boysenberry : 40,
                    blueberry: 35
                }
            };
        });
    
        describe('trees', function () {
    
            it ('should have apples and oranges', function() {
                expect (orchard.trees.apple).toBeDefined();
                expect (orchard.trees.orange).toBeDefined();
    
                expect (orchard.trees.apple).toEqual(10);
                expect (orchard.trees.orange).toEqual(20);
            });
            it ('should NOT have pears or cherries', function() {
                expect (orchard.trees.pear).toBeUndefined();
                expect (orchard.trees.cherry).toBeUndefined();
            });
        });
    });
    

    For the new comers to Jasmine, this is how you intrepret the above code :\

    1. describe defines a test suite. The test suite name here is a user defined simple string, say "simple object".
    2. A test suite can itself contain other test suites, meaning describecan contain nested suites.
    3. Just like other programming languages, orchid is global to all the functions & suites defined within simple object test suite.
    4. It block is called a specification or a SPEC. It blocks contain individual tests.
    5. Just when Jasmine executes the test cases, it will first visit the it blocks meaning it will traverse all the it block declarations.
    6. When Jasmine actually executes test cases, it will check for beforeEach function and hence orchard gets trees value assigned to it.
    7. And hence you need not write a beforeEach function, inside a sub suite. You can simply ignore

      beforeEach (function() { trees = orchard.trees; });

    8. Now compare the latest snippet below with the third snippet above.

提交回复
热议问题