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. Thanks!

Answers:

Answer

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 finished
    var myObject
    spyOn(myObject, "callback").andCallFake(function() {
        done();        
    });    
    myObject.makeAjaxCall();    
}
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.