Jasmine,Angular“rootScope。$ broadcast”测试

时间:2015-03-27 08:52:57

标签: javascript angularjs unit-testing jasmine karma-jasmine

我正在尝试为具有$rootScope.$on('accountsSet', function (event)...的控制器编写测试。所以在测试中我使用的是.broadcast.andCallThrough(),其中许多其他问题在SO中提出,而它之前也适用于我。

所以我的控制器非常简单:

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

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

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

});

任何测试都很简单:

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();

    });

});

如果spyOn(scope, '$broadcast').andCallThrough();,我会收到错误。请注意,此测试的范围是rootScope,因此这不应该是一个问题。

所以引用该行的错误: TypeError:'undefined'不是函数(评估'spyOn(范围,'$ broadcast')。andCallThrough()')         at ... / tests / controllers / sidemenu.js:30

1 个答案:

答案 0 :(得分:3)

我将评论转为答案,因为事实证明这是一个解决方案:

在jasmine 2.0中间谍的语法已经改变(还有很多其他的东西,请参阅漂亮的文档here) 新语法是

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

与jasmine 1.3语法比较:

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