3
votes

I'm trying to write a test for a controller that has $rootScope.$on('accountsSet', function (event).... So in the tests I'm using .broadcast.andCallThrough() which many other questions here in SO suggest while it also worked before for me.

So my controller is pretty simple:

angular.module('controller.sidemenu', [])

.controller('SidemenuCtrl', function($rootScope, $scope, AccountsService) {

    $rootScope.$on('accountsSet', function (event) {
        $scope.accounts = AccountsService.getAccounts();
        $scope.pro = AccountsService.getPro();
    });

});

Any the test is simple as well:

describe("Testing the SidemenuCtrl.", function () {

    var scope, createController, accountsService;

    beforeEach(function(){

        angular.mock.module('trevor');
        angular.mock.module('templates');

        inject(function ($injector, AccountsService) {

            scope = $injector.get('$rootScope');
            controller = $injector.get('$controller');
            accountsService = AccountsService;

            createController = function() {
                return controller('SidemenuCtrl', {
                    '$scope' : $injector.get('$rootScope'),
                    'AccountsService' : accountsService,
                });
            };
        });

    });

    it("Should load the SidemenuCtrl.", function () {

        accountsService.setPro(true);

        spyOn(scope, '$broadcast').andCallThrough();

        var controller = createController();

        scope.$broadcast("accountsSet", true);
        expect(scope.pro).toBeTruthy();

    });

});

The error I'm getting if for spyOn(scope, '$broadcast').andCallThrough();. Note that scope for this tests is rootScope so that shouldn't be a problem.

So the error that refers to that line: TypeError: 'undefined' is not a function (evaluating 'spyOn(scope, '$broadcast').andCallThrough()') at .../tests/controllers/sidemenu.js:30

1
Are you not using jasmine 2.0 perchance? The syntax was changed to and.callThrough() - doldt
Yes that was it! The thing is that I do have karma-jasmine: 0.3.5 and I haven't installed jasmine-core as the docs say. That's weird? - manosim
I don't think you need jasmine-core separately, not if your tests run, anyway :) If my comment was the solution, I'll turn it into a short answer which you could kindly accept. - doldt

1 Answers

4
votes

I'm turning my comment into an answer since it turned out to be the solution:

In jasmine 2.0 the syntax of spies has changed (and many other things, see the beautiful docs here) the new syntax is

spyOn(foo, 'getBar').and.callThrough();

Compare with the jasmine 1.3 syntax of:

spyOn(foo, 'getBar').andCallThrough();