Jasmine,Angular;rootScope$广播“;测验

Jasmine, Angular "rootScope.$broadcast" test

本文关键字:广播 测验 rootScope Angular Jasmine      更新时间:2023-09-26

我正试图为具有$rootScope.$on('accountsSet', function (event)...的控制器编写一个测试。所以在测试中,我使用了.broadcast.andCallThrough(),这是So中的许多其他问题建议的,而它以前也适用于我

所以我的控制器很简单:

角度模块("控制器侧菜单",[])

.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(scope,'$broadcast').andCallThrough()")在/tests/controllers/sidemenu.js:30

我要把我的评论变成一个答案,因为它原来是解决方案:

在jasmine 2.0中,间谍的语法发生了变化(还有许多其他内容,请参阅此处的漂亮文档)新语法是

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

与:的jasmine 1.3语法进行比较

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