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!
Using the done() Method in Your Jasmine-driven Asynchronous JavaScript Tests. Jasmine. Async is an add-on library for Jasmine that provides additional functionality to do asynchronous testing. Modeled after Mocha's async test support, it brings the done() function to the Jasmine unit testing environment.
it('expects testableVariable to become true', function(done) { testableCode(); setTimeout(function() { expect(testableVariable). toEqual(true); done(); }, 20); }); Additionally, the timer behavior could be mocked ... this method allows jasmine to step the time forward.
Jasmine supports three ways of managing asynchronous work: async / await , promises, and callbacks.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With