簡體   English   中英

Jasmine,Angular“rootScope。$ broadcast”測試

[英]Jasmine, Angular “rootScope.$broadcast” test

我正在嘗試為具有$rootScope.$on('accountsSet', function (event)...的控制器編寫測試$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'不是函數(在... / tests / controllers / sidemenu.js中評估'spyOn(scope,'$ broadcast')。andCallThrough()'):30

我將評論轉變為答案,因為它原來是解決方案:

在jasmine 2.0中,間諜的語法已經改變(以及許多其他的東西,請參閱這里的漂亮文檔)新語法

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

與jasmine 1.3語法相比:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM