我正在尝试使用Jasmine为AngularJS应用程序设置测试.它遵循文档,但有点简单.该小提琴具有下面的代码:
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.
如何更正代码以摆脱此错误并能够测试控制器?
您需要实例化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'); }) });
演示: https ://jsfiddle.net/f5ebb55f/6/