Unit Testing AngularJS Module Controller

I look at the TODO MVC AngularJS example, and I see that the application is defined as a module.

var todomvc = angular.module('todomvc', []);

Inside the controllers, I see that they are defined as:

todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter) {
    //...
});

My question is about unit testing ... how do I write unit test for this class?

I tried things like:

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
        });

    });
});

... but then the "controller" ends with zero or undefined.

Do I need to modify the TODO MVC application so that the function passed to todomvc.controller () is not anonymous?

Any direction would be appreciated as I am very new to Angular.

+5
source share
1 answer

You need to use the service $controllerfor the unit test controller.

Basically, you are doing something like this:

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

+10

All Articles