Jasmine spies

Spy usage guidelines

by eitanp461

HTML

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

JavaScript

"use strict";

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.and.returnValue(5);
            foo(barSpy);
            expect(barSpy.getWidth).toHaveBeenCalled();
            expect(barSpy.setHeight).not.toHaveBeenCalled();

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