Last Updated: January 05, 2018
·
370
· apelbaur

Test angular controller

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:
1. inject the $controller service
2. 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');
});

https://jsfiddle.net/ronapelbaum/tcmsw688/

Now, if you're still workng 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:
1. inject $rootScope
2. create a new scope
3. inject it to a new controller
4. test the $scope

it("test greetUpperCase()", function() {
    var $scope = $rootScope.$new();
    $controller("MyController", {
        $scope: $scope
    });
    expect($scope.greetUpperCase('bob')).toBe('HELLO BOB');
});

https://jsfiddle.net/ronapelbaum/pkhaxmdg/