问题
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