Jasmine testing async calls with beforeEach and invoking the special done callback in the promise's done callback

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
var flag = false;

function testAsyncWithDeferred() {
    // Get a jQuery deferred
    var deferred = $.Deferred();

    // Wait two seconds, then set the flag to true
    setTimeout(function () {
        flag = true;

        // Resolve the deferred
        deferred.resolve();
    }, 2000);

    // Return the deferred promise
    return deferred.promise();
}

// Specs
describe("Testing async calls with beforeEach and invoking the special done callback in the promise's done callback", function () {

    beforeEach(function(done) {
        testAsyncWithDeferred()
        .done(function (result) {
            // Invoke the special done callback
            done();
        });
    });
               
    it("Should be true if the async call has completed", function () {
        expect(flag).toEqual(true);
    });

});