Jasmine:为什么 beforeEach() 在嵌套描述中工作,而 beforeAll() 没有?

eff*_*ort 4 unit-testing jasmine angularjs

我正在努力理解为什么我的代码不起作用以及为什么当我在嵌套的描述测试套件中使用 simplebeforeAll()而不是 a时测试失败beforeEach()?这是一个概述我的问题的小例子:

describe("myService", function() {
  // Basic services
  // Some variables 

  beforeEach(module('app'));   // Invoke the module
  beforeEach(function(){

    // Inject the services
    inject(function(_myService_) {
      myService = _myService_;
    });
  });

  /************************ Add more unit tests here ************************/

  describe("myFunction", function() {
    describe("calls function with one set of input paramenters", function() {

      //beforeAll(function() {
      beforeEach(function() { // <-- Why this works but beforeAll doesn't???
        // Call myFunction with different parameters
        result = myService.myFunction(parametersType_1);
      });

      it("should do tests on result (the return from the function)", function() {
      });
    });

  describe("calls function with other set of input paramenters", function() {

    //beforeAll(function() {
    beforeEach(function() { // <-- Why this works but beforeAll doesn't???
      // Call myFunction with different parameters
      result = myService.myFunction(parametersType_2);
    });

    it("should do tests on result (the return from the function)", function() {
    });
  });
}); 
Run Code Online (Sandbox Code Playgroud)

And*_*rew 6

将您注入服务的部分更改为 beforeAll 而不是 beforeEach:

beforeAll(function(){

    // Inject the services
    inject(function(_myService_) {
    myService = _myService_;
});
Run Code Online (Sandbox Code Playgroud)

外部 describe 中的 beforeEach 不会在每个嵌套的 describe 部分之前触发,而是在描述中的每个“it”之前触发。因为内部 beforeAll 在外部描述中的 beforeEach 之前被触发,所以您试图在注入之前使用该服务。

例如:

describe("outer describe", function() {

 beforeAll(function() {
    console.log("A");   
 });

 beforeEach(function() {
    console.log("B");   
 });

 describe("inner describe", function() {
    beforeAll(function() {
        console.log("C");
    });

    beforeEach(function() {
        console.log("D");
    });

    it("test", function() {
    })'
 });

});
Run Code Online (Sandbox Code Playgroud)

将按顺序执行:A、C、B、D