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

Why is Jasmine not executing it() on this async test?

本文关键字:执行 测试 异步 Jasmine 为什么      更新时间:2023-09-26

我正在尝试测试一个原型方法,该方法返回关于我通过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(),而不是it()。一般来说,我对JavaScript测试很陌生,所以我想我做错了什么。但我不确定是什么。

另外,因为我正在处理的数据是一个巨大的 JSON文件,所以不可能将其包含在此文件中。也不可能提供一个样本大小的版本。数据集中的每个对象都有数百行长。

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

在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');
     });
  });
});

茉莉花1。x使用一种特殊的轮询机制来保持对waitsFor方法的轮询,直到超时或返回true,然后执行最后的runs方法。

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

茉莉花2。X有点不同,因为它使用一种信号机制来指示何时开始和结束测试。你的规范可以采用一个可选的done方法来同步你的测试。

如果您在beforeEach中使用done方法,那么它将不会开始您的测试,直到该方法被调用。

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

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