为什么Jasmine没有在这个异步测试中执行它()?

时间:2014-06-06 19:00:12

标签: javascript tdd jasmine

我正在尝试测试原型方法,该方法返回有关我通过AJAX加载的数据集的见解。

$.getJSON('../data/bryce.json').done(function(data) {

    insights = new Insights(data);

    describe("People Method", function() {

       console.log('it executes this far');

        it("should return complete people data", function() {

            console.log('but not this far');

            expect(insights.people()).toBeTruthy();

        });

    });

});

当我运行这个测试套件时,describe()执行,但不执行()。我对JavaScript测试一般都很陌生,所以我想我做错了。但我不确定它是什么。

此外,由于我正在使用的数据是巨大的 JSON文件,因此无法将其包含在此文件中。也不可能提供样本大小的版本。数据集中的每个对象都有数百行。

1 个答案:

答案 0 :(得分:1)

Jasmine使用排队机制并执行排队工作的所有describeit函数。

在Jasmine中异步工作需要您遵循某种模式。

Jasmine 1.x

describe('some suite', function(){

  it('some test', function(){

     var data;

     //Execute some async operation
     runs(function(){
         $.get('myurl').done(function(d){ data = d; });
     });

     //Wait for it to finish
     waitsFor(function(){
        return typeof data !== 'undefined';
     });

     //Assert once finished
     runs(function(){
        expect(data.foo).toBe('bar');
     });

  });

});

Jasmine 1.x使用特殊的轮询机制来轮询waitsFor方法,直到它超时,或返回true,然后执行最终的runs方法。

Jasmine 2.x

describe('some suite', function(){

  var data;

  beforeEach(function(done){
     $.get('myurl').done(function(d){ 
        data = d;

        //Signal test to start
        done();
     });
  });

  it('some test', function(done){
     expect(data.foo).toBe('bar');

     //Signal test is finished
     done();
  });

});

Jasmine 2.x有点不同,因为它使用信号机制来指示何时开始和完成测试。您的规范可以采用可选的done方法来同步您的测试。

如果您在done中使用beforeEach方法,那么在调用该方法之前,它将无法启动您的测试。

如果在done函数中使用it方法,则在调用该方法之前,测试将无法完成。

这两个都可以用来有效地管理测试中的异步行为。