【问题标题】:Jasmine, Angular "rootScope.$broadcast" testJasmine,Angular“rootScope.$broadcast”测试
【发布时间】:2015-03-27 08:52:57
【问题描述】:

我正在尝试为具有$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(scope, '$broadcast').andCallThrough()') 在 .../tests/controllers/sidemenu.js:30

【问题讨论】:

  • 您可能没有使用 jasmine 2.0 吗?语法改为 and.callThrough()
  • 是的,就是这样!问题是我确实有karma-jasmine: 0.3.5,但我还没有像文档所说的那样安装jasmine-core。这很奇怪?
  • 我不认为你需要单独的 jasmine-core,如果你的测试运行,无论如何:) 如果我的评论是解决方案,我会把它变成一个简短的答案,你可以接受.

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


【解决方案1】:

我正在将我的评论变成一个答案,因为事实证明它是解决方案:

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

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

与jasmine 1.3的语法比较:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-16
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多