我正在查看TODO MVC AngularJS示例,我看到应用程序被定义为模块。
var todomvc = angular.module('todomvc', []);
在控制器内部,我看到它们被定义为:
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter) {
//...
});
我的问题涉及单元测试......如何为该课程编写单元测试?
我尝试过这样的事情:
describe('TodoCtrl', function () {
var controller;
beforeEach(function () {
controller = todomvc.TodoCtrl;
});
afterEach(function() {
controller = null;
});
describe('addTodo() method', function() {
console.log(controller)
it('should do something', function () {
expect(typeof controller.addTodo).toBe(true); //should fail
});
});
});
...但是“控制器”最终变为空或未定义。
我是否需要修改TODO MVC应用程序,以便传递给 todomvc.controller()的函数不是匿名的?
任何方向都会受到赞赏,因为我对Angular很新。
答案 0 :(得分:10)
您需要使用$controller
服务对控制器进行单元测试。
基本上,你做的是这样的事情:
var scope, ctrl;
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('TodoCtrl', {$scope: scope});
}));
//use scope and ctrl as needed
请参阅此处的示例:https://github.com/angular/angular-phonecat/blob/master/test/unit/controllersSpec.js#L18