silkAdmin silkAdmin - 3 years ago 165
Javascript Question

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() a few milliseconds before running expectation and that worked fine. However with jasmine 2.0 wait() is deprecated and it now seems that everything inside a setTimeout do not get run unless done() is called, witch in my case doesn't cut it as i actually want to wait real time before running my expectation..

Not sure if that all make sense, if it does I'd love some pointers on how I could go about this.

Answer Source

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();
    waitsFor(function() {
        return callback.callCount > 0;
    }, "The Ajax call timed out.", 5000);

    runs(function() {


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 finished
    var myObject
    spyOn(myObject, "callback").andCallFake(function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download