1

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

        });
4

1 回答 1

2

spyOn不调用你的方法。它只是间谍。如果你想调用它,你必须添加一些东西:

spyOn(scope, "trigger").andCallThrough()
于 2014-04-18T15:41:58.053 回答