TypeError:在使用Jasmine的Angular控制器单元测试中未定义$ scope

时间:2014-04-03 22:08:50

标签: angularjs unit-testing controller jasmine

这是一个非常简单,非常简化的测试和控制器。我的控制器'LedgerCtl'有一个注入的服务'LedgerService',我在别处测试,所以在我的LedgerControllerSpec中我创建了一个替代模拟服务的函数。当我执行测试时,我得到'范围未定义'错误。 thisthis是我找到的最接近的答案;然而,两者都没有解决我的问题。

angular.module("TeamSportApp", [])
.controller('LedgerCtl', function($scope, LedgerService) {
    $scope.ledger = [];
    // init controller by getting list of pics
    $scope.getLedger = function() {
        $scope.ledger = LedgerService.getLedger();
    };
    // init list
    $scope.getLedger();
})

和规范

var ledgerStaticData = [
{ "ID": 1, "Name": "Item1", Balance: 2100 },
{ "ID": 2, "Name": "Item2", Balance: 3300 },
{ "ID": 3, "Name": "Item3", Balance: 2000 },
{ "ID": 4, "Name": "Item4", Balance: 1500 }
];



describe('controllers', function(){
var ctrl, mockLedgerService, $scope;

beforeEach(module('TestApp',[]));
beforeEach(inject(function($rootScope, $controller) {

    mockLedgerService = {
        getLedger: function() {}
    };

    spyOn(mockLedgerService, 'getLedger').andReturn(ledgerStaticData);
    $scope = $rootScope.$new();
    ctrl = $controller('LedgerCtl', {$scope: $scope , LedgerService: mockLedgerService });
}));

it('Should call mockLedgerService getLedger', function() {
    expect($scope.ledger.length).toBe(4);   <<<--- SCOPE UNDEFINED HERE
});
});

1 个答案:

答案 0 :(得分:1)

您的测试不会加载定义控制器的模块(TeamSportApp)。添加以下行:

beforeEach(module('TeamSportApp'));

此外,不需要定义以下空模块:

beforeEach(module('TestApp',[]));