Testing asynchronous code
Jasmine can test asynchronous code using an alternative specification pattern. The beforeEach
, afterEach
, and it
global functions can receive an argument, which is a particular helper function that we have to use in this situation.
The asynchronous test pattern can be summarized in the following example (03_07.js
). Think about a typical service that executes an ajax
request:
var MyService = function () { this.fetchResult = function (callback) { jQuery.ajax("url", { success: function (result) { callback(result); } }); }; };
The fetchResult
method takes a callback function as an argument, which is called by passing the result when the Ajax call is successful.
If we want to test this JavaScript class, we can write the following spec (03_07_specs.js
):
describe("Given an async service", function () {
var myService, myResult;
beforeEach(function (done) {
myService = new MyService();
spyOn...