2017-03-03 48 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); 
    }); 
}); 
相關問題