TypeError: $scope is undefined in Angular controller unit test with Jasmine

一个人想着一个人 提交于 2019-12-08 06:53:10

问题


This is a very simple, quite pared down test and controller. My controller 'LedgerCtl' has an injected service 'LedgerService' that I test elsewhere, so in my LedgerControllerSpec I created a function that stands-in for the mocked service. When I execute the test, I get the 'scope undefined' error. this and this are the closest answers I found; however neither solve my issue.

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();
})

and the spec

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:


Your test doesn't load the module where the controller is defined (TeamSportApp). Add the following line:

beforeEach(module('TeamSportApp'));

Also, defining the following empty module is unnecessary:

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


来源:https://stackoverflow.com/questions/22849953/typeerror-scope-is-undefined-in-angular-controller-unit-test-with-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!