Conditionally ignore individual tests with Karma / Jasmine

Zach Lysobey picture Zach Lysobey · Aug 26, 2015 · Viewed 22.9k times · Source

I have some tests that fail in PhantomJS but not other browsers.

I'd like these tests to be ignored when run with PhantomJS in my watch task (so new browser windows don't take focus and perf is a bit faster), but in my standard test task and my CI pipeline, I want all the tests to run in Chrome, Firefox, etc...

I've considered a file-naming convention like foo.spec.dont-use-phantom.js and excluding those in my Karma config, but this means that I will have to separate out the individual tests that are failing into their own files, separating them from their logical describe blocks and having more files with weird naming conventions would generally suck.

In short:

Is there a way I can extend Jasmine and/or Karma and somehow annotate individual tests to only run with certain configurations?

Answer

milanlempera picture milanlempera · Sep 1, 2015

Jasmine supports a pending() function.

If you call pending() anywhere in the spec body, no matter the expectations, the spec will be marked pending.

You can call pending() directly in test, or in some other function called from test.

function skipIfCondition() {
  pending();
}

function someSkipCheck() {
  return true;
}

describe("test", function() {
  it("call pending directly by condition", function() {
    if (someSkipCheck()) {
      pending();
    }

    expect(1).toBe(2);
  });

  it("call conditionally skip function", function() {
    skipIfCondition();

    expect(1).toBe(3);
  });

  it("is executed", function() {
    expect(1).toBe(1);
  });

});

working example here: http://plnkr.co/edit/JZtAKALK9wi5PdIkbw8r?p=preview

I think it is purest solution. In test results you can see count of finished and skipped tests.