Skip to content Skip to sidebar Skip to footer

Jasmine 2.0 How To Wait Real Time Before Running An Expectation

I am trying to test the postMessage API as there is a slight delay before message are receive i can not run expectation right after sending a message. In jasmine 1.3 i used to wait

Solution 1:

This works for me:

beforeAll(function (done) {
    setTimeout(done, 5000);
});

The beforeAll function occurred first, but it will end when you invoke the done callback function. So if you use setTimeout function with 5000, it will wait 5000 milliseconds before continuing.

Solution 2:

Rather than waiting some number of milliseconds, jasmine has hooks to wait until a function returns. This page has some good example, and I've copied one here to show a specific way of testing ajax callbacks. Just add a spy as a callback to your function and wait for that callback to be executed.

it("should make a real AJAX request", function () {
    var callback = jasmine.createSpy();
    makeAjaxCall(callback);
    waitsFor(function() {
        return callback.callCount > 0;
    }, "The Ajax call timed out.", 5000);

    runs(function() {
        expect(callback).toHaveBeenCalled();
    });
});

EDIT:

Since you're testing that your application makes a specific callback, you can just replace that callback with a spy instead of creating a new one like I did.

Jasmine 2.0 added a "done" style callback, so you should be able to do something like: (I haven't tested the syntax of this but hopefully a good start)

it("should make an ajax callback with jasmine 2.0", function(done)) {
    // this is the object you are testing - assume it has the ajax method you want to call and the method that gets called when the ajax method is finishedvar myObject
    spyOn(myObject, "callback").andCallFake(function() {
        done();        
    });    
    myObject.makeAjaxCall();    
}

Post a Comment for "Jasmine 2.0 How To Wait Real Time Before Running An Expectation"