Jasmine cheat sheet - spy matchers

Demonstrating Jasmine spy matchers

by munir

HTML

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

JavaScript

describe("A spy", function () {
    var foo, bar = null;

    beforeEach(function () {
        foo = {
            setBar: function (value) {
                bar = value;
            }
        };

        spyOn(foo, 'setBar');

        foo.setBar(123);
        foo.setBar(456, 'another param');
    });

    it("tracks that the spy was called", function () {
        expect(foo.setBar).toHaveBeenCalled();
    });

    it("tracks its number of calls", function () {
        expect(foo.setBar.calls.length).toEqual(2);
    });

    it("tracks all the arguments of its calls", function () {
        expect(foo.setBar).toHaveBeenCalledWith(123);
        expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
    });

    it("allows access to the most recent call", function () {
        expect(foo.setBar.mostRecentCall.args[0]).toEqual(456);
    });

    it("allows access to other calls", function () {
        expect(foo.setBar.calls[0].args[0]).toEqual(123);
    });

    it("stops all execution on a function", function () {
        expect(bar).toBeNull();
    });

    it("simulates throwing exceptions", function () {
        foo.setBar.reset();
        foo.setBar.andThrow(new Error('my exception'));
        expect(function () {
            foo.setBar()
        }).toThrow();
    });

    it("can be retrained", function () {
        foo.setBar.reset();
        foo.setBar.andReturn('first');
        expect(foo.setBar()).toEqual('first');
        foo.setBar.andReturn('second');
        expect(foo.setBar()).toEqual('second');
    });
    
});

// 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)...