Jasmine异步错误:超时 - 在jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超时内未调用异步回调

时间:2017-03-03 20:12:30

标签: javascript unit-testing jasmine

Jasmine新手,我正在测试一个async函数。它显示错误Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.如果我在这里遗漏了某些内容,请提供帮助。

测试功能:

function AdressBook(){
   this.contacts = [];
   this.initialComplete = false;
}
AdressBook.prototype.initialContact = function(name){
   var self = this;
   fetch('ex.json').then(function(){
       self.initialComplete = true;
       console.log('do something');
   });
}

测试规格如下:

var addressBook = new AdressBook();
     beforeEach(function(done){
         addressBook.initialContact(function(){
             done();
         });
     });
     it('should get the init contacts',function(done){
          expect(addressBook.initialComplete).toBe(true);
          done();
     });

1 个答案:

答案 0 :(得分:0)

来源

function AddressBook() {
    this.contacts = [];
    this.initialComplete = false;
}

AddressBook.prototype.initialContact = function(name) {
    var self = this;
    // 1) return the promise from fetch to the caller
    return fetch('ex.json').then(function() {
            self.initialComplete = true;
            console.log('do something');
        }
        /*, function (err) {
              ...remember to handle cases when the request fails 
           }*/
    );
}

测试

describe('AddressBook', function() {
    var addressBook = new AddressBook();
    beforeEach(function(done) {
        // 2) use .then() to wait for the promise to resolve
        addressBook.initialContact().then(function() {
            done();
        });
    });
    // done() is not needed in your it()
    it('should get the init contacts', function() {
        expect(addressBook.initialComplete).toBe(true);
    });
});
相关问题