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!
4 Answers
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).
-
1You may introduce a code-smell if you mutate a state in an `it` block. The `it` blocks are solely for logic-less asserts. – gnerkus Aug 30 '15 at 06:56
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.

- 3,234
- 20
- 41
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();

- 6,965
- 26
- 32
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.

- 896
- 9
- 14
-
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". – user3037143 Jun 20 '14 at 06:15