2013-03-08 176 views
5

我正在看TODO MVC AngularJS示例,并且我看到该应用程序被定义为一个模块。单元测试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 
     }); 

    }); 
}); 

...但随后 “控制器” 最终是null或undefined。

我是否需要修改TODO MVC应用程序,以便传递给todomvc.controller()的函数不是匿名的?

任何方向将不胜感激,因为我是非常新的Angular。

回答

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

+0

我会检查出来,谢谢! – arthurakay 2013-03-08 21:19:21

+0

这个例子的确有很大的帮助......但是我仍然得到一个“TodoCtrl is not defined”的错误,这让我觉得我需要改变TODO MVC例子中控制器的写法(使它更像你链接的例子)。但我在正确的轨道上,谢谢! – arthurakay 2013-03-08 21:30:37

+0

经过进一步检查,在使用您的建议后,我必须使用“scope.addTodo()”而不是“ctrl.addTodo()”。谢谢! – arthurakay 2013-04-09 18:05:15