描述在Jasmine Javascript中等待异步的功能

时间:2015-07-20 10:00:00

标签: javascript jasmine

我正在使用done处理Jasmine中的异步代码。它的功能是等到beforeAll完成但描述函数没有等待......

这是我的代码。

describe("xyz", function(){
var d;     
     beforeAll(function(done){
       $.getJSON( "path/abc.json", function( data ) {
         d = data;
         done();
       });
     });
     describe("some scenario", function(){
         // d value is undefined here 
         it("spec1", function(){ 
         // it is waiting until beforeAll function is done        
          expect().toBe();
        });
        it("spec2", function(){

          expect().toBe();
        });

        });
     });

     describe("scenario 2", function(){
        it("spec3", function(){
          expect().toBe();
        });
        it("spec 4", function(){
          expect().toBeGreaterThan();
        });
     });
});

1 个答案:

答案 0 :(得分:0)

试着想象一下如何运行测试。

首先运行描述创建测试套件的函数。 内部套件是函数(beforeAll / Each,after ...)和注册的测试 - 分配给队列。

随后执行西装。

如果您在测试中记录所有功能,则可以看到运行顺序(http://plnkr.co/edit/kxX5TAwHOqRRMFjvE5FZ?p=preview

describe("xyz", function() {
  console.log("describe xyz - start");

  var d;
  beforeAll(function(done) {
    console.log("beforeAll");
    setTimeout(function() {
      d = 1234;
      done()
    }, 1000);
  });
  describe("some scenario", function() {
    console.log("describe some scenario - start");

    var d2;
    // d value is undefined here 
    beforeEach(function() {
      console.log("beforeEach");
      d2 = d;
    })

    it("spec1", function() {
      console.log("spec1");
      // it is waiting until beforeAll function is done        
      expect(d).toBe(1234);
    });
    it("spec2", function() {
      console.log("spec2");

      expect(d2).toBe(1234);
    });

    console.log("describe some scenario - end");
  });

  console.log("describe xyz - end");
});

-

describe xyz - start
describe some scenario - start
describe some scenario - end
describe xyz - end
beforeAll
beforeEach
spec1
beforeEach
spec2

这意味着所有可执行代码都应该在* / after *之前的函数内部。

相关问题