BeforeAll and AfterAll in javascript test cases
Asked Answered
T

4

9

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!

Tishatishri answered 12/2, 2014 at 11:18 Comment(0)
M
9

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).

Merlinmerlina answered 23/6, 2014 at 15:3 Comment(1)
You may introduce a code-smell if you mutate a state in an it block. The it blocks are solely for logic-less asserts.Goatsucker
D
7

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.

Diep answered 16/4, 2015 at 10:53 Comment(0)
S
0

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();
Snips answered 12/2, 2014 at 13:50 Comment(0)
B
0

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.

Bloomfield answered 12/2, 2014 at 15:29 Comment(1)
Check the Jasmine2.0 standalone release, the location of the file is "jasmine-standalone-2.0.0\lib\jasmine-2.0.0\jasmine-html.js".Bloomfield

© 2022 - 2024 — McMap. All rights reserved.