2015-07-20 115 views
0

我正在使用done处理Jasmine中的异步代码。它的功能正在等待,直到beforeAll完成但描述功能并未等待...描述函数不等待,直到在Jasmine中完成异步完成Javascript

这是我的代码。

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(); 
     }); 
    }); 
}); 

回答

0

试着想象如何运行测试。

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

诉讼随后被执行。

如果登录测试的所有功能,你可以看到运行秩序(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 

这意味着所有的可执行代码应该是内部功能*前/后*或者它。