Jasmine在我的第三个规范中抛出了一个错误。 错误:超时 - 在jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超时时间内未调用异步回调。
这是我的spec文件
describe('Address Book', function(){
var addressBook,
thisContact;
beforeEach(function(){
addressBook = new AddressBook(),
thisContact = new Contact();
});
it('Should be able to add a contact', function(){
addressBook.addContact(thisContact);
expect(addressBook.getContact(0)).toBe(thisContact);
});
it('Should be able to delete a contact', function(){
addressBook.addContact(thisContact);
addressBook.delContact(1);
expect(addressBook.getContact(1)).not.toBeDefined();
});
});
describe('Async Address Book', function(){
var addressBook = new AddressBook();
beforeEach(function(done){
addressBook.getInitialContacts(function(){
done();
});
});
it('Should be able to add a contact', function(done){
expect(addressBook.initialContacts).toBe(true);
done();
});
});
这是我的src文件
function AddressBook(){
this.contacts = [];
this.initialContacts = false;
}
AddressBook.prototype.getInitialContacts = function(cb){
var self = this;
setTimeout(function(){
self.initialContacts = true;
if (cb) {
return cb;
}
}, 3);
}
AddressBook.prototype.addContact = function(contact){
this.contacts.push(contact);
}
AddressBook.prototype.getContact = function(index){
return this.contacts[index];
}
AddressBook.prototype.delContact = function(index){
this.contacts.splice(index,1);
}
我没有得到这个问题..请看一下......提前谢谢。
答案 0 :(得分:3)
问题在于getInitialContacts
功能。它永远不会调用提供的回调它只返回它。
AddressBook.prototype.getInitialContacts = function(cb){
var self = this;
setTimeout(function(){
self.initialContacts = true;
if (cb) {
return cb;
}
}, 3);
}
应该更改为在异步操作完成时调用回调:
AddressBook.prototype.getInitialContacts = function(cb){
var self = this;
setTimeout(function(){
self.initialContacts = true;
if (typeof cb === 'function') {
cb();
}
}, 3);
}