angular controller test
Testing controller with controllerAs
After we’ve seen how to test a service, let’s talk about testing a controller.
function MyController(MyService) {
this.greetUpperCase = function(name) {
return MyService.greet(name).toUpperCase();
}
}
We’d like angular’s DI to inject an instance of our controller to our test, but controllers are not singltons as services.
Therefore, we will:
-
inject the $controller service
-
use it to instance a controller for us
var $controller;
beforeEach(module('MyModule'));
beforeEach(inject(function(_$controller_) {
$controller = _$controller_; })
);
it('test greetUpperCase()', function() {
var ctrl = $controller('MyController');
expect(ctrl.greetUpperCase('bob')).toBe('HELLO BOB');
});
Testing controller with $scope
Now, if you’re still working with $scope:
function MyController($scope, MyService) {
$scope.greetUpperCase = function(name) {
return MyService.greet(name).toUpperCase();
}
}
Basically, when you’re working with $scope, you don’t really care about the controller itself, since it’s doing everything on it’s scope.
So, we will need to:
- inject $rootScope
- create a new scope
- inject it to a new controller
- test the $scope
it('test greetUpperCase()', function() {
var myScope = $rootScope.$new();
$controller('MyController', {
$scope: myScope
});
expect(myScope .greetUpperCase('bob')).toBe('HELLO BOB');
});