Jasmine cheat sheet - spies usage guidelines

Demonstrating applicability of spies usage

by manoj

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("spy usage guidelines", function () {

    describe("spyOn", function () {
        it("is used to spy on interactions of code under test with existing objects",

        function () {
            // Source
            var foo = function () {
                console.log('Hello World');
            };

            // Test
            spyOn(console, 'log');
            foo();
            expect(console.log).toHaveBeenCalledWith('Hello World');
        });
    });

    describe("createSpy", function () {
        it("is used for functions called by the code under test with no return value, usually callbacks",

        function () {
            // Source
            var foo = function (callback) {
                callback('Hello World');
            };

            // Test
            var callbackSpy = jasmine.createSpy('spy name');
            foo(callbackSpy);
            expect(callbackSpy).toHaveBeenCalledWith('Hello World');
        });
    });

    describe("createSpyObj", function () {
        it("is used interactions of code under test with dependencies, usually other classes",

        function () {
            // Source
            var foo = function (bar) {
                var x = bar.getWidth();
                if (x > 10) {
                    bar.setHeight(x);
                }
            }

            // Test
            var barSpy = jasmine.createSpyObj('spy name', ['getWidth', 'setHeight']);
            barSpy.getWidth.andReturn(5);
            foo(barSpy);
            expect(barSpy.getWidth).toHaveBeenCalled();
            expect(barSpy.setHeight).not.toHaveBeenCalled();

            barSpy.getWidth.andReturn(100);
            foo(barSpy);
            expect(barSpy.getWidth).toHaveBeenCalled();
            expect(barSpy.setHeight).toHaveBeenCalledWith(100);
        });
    });
});

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

    var trivialReporter = new...