9
votes

First of all, the below code seems to work. However, I have not yet seen anyone do this so I am wondering if this is even legitimate and if I am missing unforeseen downsides.

The context is that I am writing an E2E test with Protractor which uses Jasmine-style describe/it blocks. My goal is to load a page and run a bunch of it tests blocks without reloading that page each time (because its time consuming).

The construct I have is:

describe("Homepage", function () {

    beforeEach(function () {
        browser.get("/"); //loads the page
    });

    it('elements', function () {
        describe('test group', function () {
            it('test 1', function () {
                //run stuff 1
            });

            it('test2', function () {
                //run stuff 2
            });
        })
    });
});

I realize an alternative is just to do this:

describe("Homepage", function () {

    beforeEach(function () {
        browser.get("/"); //goes to homepage
    });

    it('elements', function () {
        //run stuff 1
        //run stuff 2

    });
});

But the issue is that I can't separate the tests and you end up with a big it block. I want to somehow avoid the issue of running beforeEach every single time but still be able to have a nicely separated set test blocks.


By the way, I have also tried this:

describe("Homepage", function () {

    browser.get("/"); //goes to homepage

    it('elements', function () {
        //run stuff 1
        //run stuff 2

    });
});

except this doesn't work when you have multiple specs like this. The browser.get() all run one after the other before the tests get run.

2

2 Answers

7
votes

Breaking the assertions into smaller it blocks is definately a good idea. Jasmine does not appead to have a global setup function that only runs once. So maybe you can trick the beforeEach block into only running the setup once:

describe("Homepage", function() {
    var pageLoaded = false;

    beforeEach(function() {
        if ( ! pageLoaded) {
            browser.get("/");
            pageLoaded = true;
        }
    });
});
4
votes

Jasmine2 has beforeAll() and afterAll() which runs once for the whole suite.