Jasmine cheat sheet - spies

Demonstrating andCallFake functionality

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

describe("A spy, when faking a return value", function () {
    var foo, bar, fetchedBar;

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

        spyOn(foo, 'getBar').andCallFake(function () {
            return 200;
        });

        foo.setBar(123);
        fetchedBar = foo.getBar();
    });

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

    it("should not affect other functions", function () {
        expect(bar).toEqual(123);
    });

    it("redirects calls to mock implementation", function () {
        expect(fetchedBar).toEqual(1);
    });
});

// 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';
    }

})();