问题
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!
回答1:
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).
回答2:
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:
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();
回答4:
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.
来源:https://stackoverflow.com/questions/21726469/beforeall-and-afterall-in-javascript-test-cases