BeforeAll and AfterAll in javascript test cases

天涯浪子 提交于 2019-12-08 18:16:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!