Jasmine testing async calls with beforeEach and invoking the special done callback in the promise's done callback and using the promise's return data
Uses Jasmine 3.5
by Joe Wilson
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.5.0/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.5.0/jasmine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.5.0/jasmine-html.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.5.0/boot.min.js"></script>
JavaScript
// Code under test
function testAsyncRealWorld() {
// Get a jQuery deferred
var deferred = $.Deferred();
// Real world data call
var data = $.getJSON("https://data.colorado.gov/resource/4ykn-tg5h.json", function() {
deferred.resolve(true);
});
// Return the deferred promise
return deferred.promise();
}
// Specs
describe("Testing async calls with real-world data", function () {
var data = null;
beforeEach(function (done) {
testAsyncRealWorld()
.done(function (result) {
data = result;
// Invoke the special done callback
done();
});
});
it("Should have result if the async call has completed", function () {
expect(data).not.toBeNull();
});
});