Question

I have an spec that test's if the method in scope was called (see below)

describe("Event Module tests", function () {

    var scope, simpleController;

    beforeEach(module('SimpleApplication'));
    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        simpleController = $controller("SimpleController", {
            $scope: scope
        });
    }));


    it("Scope function should be triggered", function () {

        spyOn(scope, "trigger");

        scope.trigger();//invoke the function on controller

        expect(scope.trigger).toHaveBeenCalled();//Passes
        expect(scope.isTriggered).toBeTruthy();//Fails

    });

});

Application Code(Code to be tested):

angular
    .module("SimpleApplication", [])
    .controller("SimpleController", function ($scope) {

        $scope.message = "Hello World";

        $scope.isTriggered = false;

        $scope.trigger = function() {
            $scope.isTriggered = true;
        };
    });

Jasmine reports that "Expected false to be truthy.". How come ? since the method sets it to true !!

Update:

For some reason, SpyOn was mutating my object to something it was intended for. So below piece of code works good

it("Scope function should be triggered", function () {

            scope.trigger();//invoke the function on controller

            expect(scope.isTriggered).toBeTruthy();//Now Passes

        });
Was it helpful?

Solution

spyOn doesn't call your method. It just spies. If you want it to be called you have to add something:

spyOn(scope, "trigger").andCallThrough()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top