user2996905
user2996905

Reputation: 125

BeforeAll and AfterAll in javascript test cases

I want do something before all tests, then after? What is the best way to organize my code? For example: backup some variables -> clear them -> test something -> restore backups. 'beforeEach' and 'afterEach' are too expencive. Thanks!

Upvotes: 9

Views: 8078

Answers (4)

edan
edan

Reputation: 1168

A pretty simple solution:

describe("all o' my tests", function() {

  it("setup for all tests", function() {
    setItUp();
  });

  describe("actual test suite", function() {

  });

  it("tear down for all tests", function() {
    cleanItUp();
  });

});

This has the advantage that you can really put your setup/teardown anywhere (eg. at the begining/end of a nested suite).

Upvotes: 9

Frank van Wijk
Frank van Wijk

Reputation: 3252

Jasmine >=2.1 supports beforeAll/afterAll for doing one-time setups and teardowns for your suite.

If you are using Jasmine 1.x you could use an it for that (as suggested by others) or load a node_module that supports beforeAll/afterAll, for example jasmine-before-all.

Upvotes: 7

user3037143
user3037143

Reputation: 926

Jasmine provides options to write your own reporter and attach it. To implement a reporter, there are basic callbacks like initialize, jasmineStarted and jasmineDone. With this you can achieve your requirement. For example, in Jasmine 2.0, refer to jasmine-html.js file to have a basic understanding.

Upvotes: 0

Eric
Eric

Reputation: 6995

Calling a function before all tests start is trivial; however, Jasmine (1.3.1, at least) doesn't allow you to specify your own finished callback outside of the reporter API.

Here's a quick little hack I found on Google Groups. Add this to your SpecRunner.html or equivalent.

var oldCallback = jasmineEnv.currentRunner().finishCallback;

jasmineEnv.currentRunner().finishCallback = function () {
    oldCallback.apply(this, arguments);

    // Do your code here
};

jasmineEnv.execute();

Upvotes: 0

Related Questions