javascript - Jasmine ,Angular "rootScope.$broadcast"测试

标签 javascript angularjs unit-testing jasmine karma-jasmine

我正在尝试为具有 $rootScope.$on('accountsSet', function (event)... 的 Controller 编写测试。所以在测试中我使用 .broadcast.andCallThrough() SO 中提出的许多其他问题,同时它以前也对我有用。

所以我的 Controller 非常简单:

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 中,spies 的语法发生了变化(还有许多其他的东西,请参阅漂亮的文档 here) 新语法是

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

与 jasmine 1.3 语法比较:

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

关于javascript - Jasmine ,Angular "rootScope.$broadcast"测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29296608/

相关文章:

linux - Test::MockTime 在某些情况下不会模拟时间

unit-testing - 如何从CDN注入(inject)外部JS到Jest单元测试?

node.js - 如何在 Jest 和 typescript 中发出错误事件

javascript - 兑现 promise ?

javascript - Bootstrap 4 Modal 由 ajax 调用打开 - 关闭按钮不起作用

javascript - 用 esc 键隐藏一个 div,然后关闭点击?在查询中

javascript - 注入(inject) $location 时 $routeProvider 不工作

javascript - Node.js 强大的文件上传在服务器上运行缓慢

javascript - 使用 jQuery 从 JS 数组动态创建 HTML 表

json - 解析 JSON 并在 Angular 中显示数据