2017-03-03 63 views
0

Jasmine新手,我正在测试一个async函数。它显示错误说Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.如果我在这里失去了一些东西,请帮忙。Jasmine异步错误:超时 - 在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(); 
    }); 

回答

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); 
    }); 
}); 
相关问题