我正在尝试使用Jasmine为AngularJS app设置测试。它遵循docs,但有点简单。 fiddle具有以下代码:
angular.module('myapp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
$scope.greeting = "hello";
}]);
describe('My controller', function() {
var $controller;
module('myapp');
inject(function(_$controller_) {
$controller = _$controller_;
});
it('greets', function() {
var $scope = {};
var controller = $controller('MyCtrl', {
$scope: $scope
});
expect($scope.greeting).toEqual('hello');
})
});
Jasmine报告错误:TypeError: $controller is not a function.
如何纠正代码以摆脱此错误并能够测试控制器?
答案 0 :(得分:7)
您需要实例化app模块,并使用$controller
块为每个测试注入beforeEach
:
describe('My controller', function() {
var $controller;
beforeEach(module('myapp'));
beforeEach(inject(function(_$controller_) {
$controller = _$controller_;
}));
it('greets', function() {
var $scope = {};
var controller = $controller('MyCtrl', {
$scope: $scope
});
expect($scope.greeting).toEqual('hello');
})
});