最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unit Testing AngularJS module controller - Stack Overflow

programmeradmin0浏览0评论

I'm looking at the TODO MVC AngularJS example, and I see the application is defined as a module.

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

Inside the controllers, I see them defined as:

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

My question deals with unit testing... how do I write a unit test for that class?

I've 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 "controller" ends up being null or undefined.

Do I need to modify the TODO MVC app so that the function passed to todomvc.controller() isn't anonymous?

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

I'm looking at the TODO MVC AngularJS example, and I see the application is defined as a module.

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

Inside the controllers, I see them defined as:

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

My question deals with unit testing... how do I write a unit test for that class?

I've 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 "controller" ends up being null or undefined.

Do I need to modify the TODO MVC app so that the function passed to todomvc.controller() isn't anonymous?

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

Share Improve this question asked Mar 8, 2013 at 19:56 arthurakayarthurakay 5,6518 gold badges39 silver badges65 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You need to used the $controller service to unit test the controller.

Basically, you do 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

See the example here: https://github./angular/angular-phonecat/blob/master/test/unit/controllersSpec.js#L18

发布评论

评论列表(0)

  1. 暂无评论