2
votes

Jasmine throws one error for my third spec. Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

here is my spec file

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

});

Here is my src file

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

I didn't get the issue.. Please take a look.. thanks in advance.

1

1 Answers

3
votes

Problem is with getInitialContacts function. It never invokes provided callback it just returns it.

    AddressBook.prototype.getInitialContacts = function(cb){

        var self = this;

        setTimeout(function(){
            self.initialContacts = true;
            if (cb) {
                return cb;
            }
        }, 3);

    }

It should be changed to invoke callback when async operation is finished:

AddressBook.prototype.getInitialContacts = function(cb){

    var self = this;

    setTimeout(function(){
        self.initialContacts = true;
        if (typeof cb === 'function') {
            cb();
        }
    }, 3);

}