Jasmine cheat sheet - async specs

Demonstrating Jasmine async specs

by eitanp461

HTML

<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">

JavaScript

var Controller = function(uploadService) {
    // Call service after 500 msec
    setTimeout(function() {
       uploadService.upload('data');
    }, 500);
}

describe("Async spec", function () {

    it("waits for async operations", function () {
        // Create spy
        var service = jasmine.createSpyObj('MyService', ['upload']);

        // Create component under test
        var controller = new Controller(service);

        // Verify that spy is not called synchronously
        expect(service.upload).not.toHaveBeenCalled();

        // Wait for spy to be called up to timeout
        waitsFor(function() {
            return service.upload.callCount > 0;
        }, 'mock service as never called', 1000);

        // Run verifications after waitsFor completes successfully
        runs(function() {
            expect(service.upload).toHaveBeenCalledWith('data');
            // mostRecentCall.args: returns argument array from last call to spy.
            expect(service.upload.mostRecentCall.args).toEqual(['data']);
        });
    });
});

// Jasmine spec runner
(function () {
    var jasmineEnv = jasmine.getEnv();
    jasmineEnv.updateInterval = 1000;

    var trivialReporter = new jasmine.TrivialReporter();

    jasmineEnv.addReporter(trivialReporter);

    jasmineEnv.specFilter = function (spec) {
        return trivialReporter.specFilter(spec);
    };

    var currentWindowOnload = window.onload;

    window.onload = function () {
        if (currentWindowOnload) {
            currentWindowOnload();
        }
        execJasmine();
    };

    function execJasmine() {
        jasmineEnv.execute();
        trivialReporter.outerDiv.className += ' show-passed';
    }

})();