9

I am currently writing tests protractor and I was wondering if there is some possibility to cancel test execution as soon as something in the beforeEach fails (and return some useful message like "precondition failed: could not login user"). I.e. I have some helper methods in the beforeEach that login the user and then do some setup.

beforeEach:
  1) login user
  2) set some user properties

Obviously it does not make any sense to execute the 2nd step if the first one fails (actually its quite harmful as the user gets locked which is not nice). I tried to add an "expect" as part of the 1st step, but the 2nd step was still executed -> fresh out of ideas.

FrankyBoy
  • 1,865
  • 2
  • 18
  • 32
  • Do you have 2 beforeEach block? Merge them and check the first parts result and run the second part only if the first finished fine. – Lajos Veres Apr 17 '14 at 16:06
  • No, its two functions called in one block. Also the main question is rather: how can I then prevent the TC from running altogether because I already know it will fail? – FrankyBoy Apr 17 '14 at 16:31

4 Answers4

2

Strictly answering your question and without external dependencies:

beforeEach(function() {
    // 1) login user
    expect(1).toBe(1);
    // This works on Jasmine 1.3.1
    if (this.results_.failedCount > 0) {
        // Hack: Quit by filtering upcoming tests
        this.env.specFilter = function(spec) {
            return false;
        };
    } else {
        // 2) set some user properties
        expect(2).toBe(2);
    }
});

it('does your thing (always runs, even on prior failure)', function() {
    // Below conditional only necessary in this first it() block
    if (this.results_.failedCount === 0) {
        expect(3).toBe(3);
    }
});

it('does more things (does not run on prior failure)', function() {
    expect(4).toBe(4);
});

So if 1 fails, 2,3,4,N won't run as you expect.

There is also jasmine-bail-fast but I'm not sure how it will behave in your before each scenario.

Community
  • 1
  • 1
Leo Gallucci
  • 16,355
  • 12
  • 77
  • 110
2
jasmine.Env.prototype.bailFast = function() {
  var env = this;
  env.afterEach(function() {
    if (!this.results().passed()) {
      env.specFilter = function(spec) {
        return false;
      };
    }
  });
};

then just call:

jasmine.getEnv().bailFast();

(credit goes to hurrymaplelad who wrote an npm that does just that, however you don't need to use it)

Gal Margalit
  • 5,525
  • 6
  • 52
  • 56
0

jasmine-bail-fast does exactly what you did overriding the specFilter function, but does it on afterEach. So it will only fail after the first "it" is run. It won't help solving this specific case.

Mourasman
  • 1
  • 2
0

with jasmine2 we can set throwOnExpectationFailure to true.

For example in protractor config:

//protractor.conf.js
exports.config = {
  //...
  onPrepare: () => {
    jasmine.getEnv().throwOnExpectationFailure(true);
  }
};
DEY
  • 1,770
  • 2
  • 16
  • 14