在测试中使用angular.module().controller()



我用module().controller()语法创建我的控制器。

angular.module('App', []);
angular.module('App').controller('PhoneListCtrl', ['$scope', function ($scope) {
    'use strict';
    $scope.phones = [
        {
            "name": "Nexus S",
            "snippet": "Fast just got faster with Nexus S."
        },
        {
            "name": "Motorola XOOM™ with Wi-Fi",
            "snippet": "The Next, Next Generation tablet."
        },
        {
            "name": "MOTOROLA XOOM™",
            "snippet": "The Next, Next Generation tablet."
        }
    ];
}]);

效果很好。但是现在我想用jasmine来测试它,我的测试用

来响应

ReferenceError: AppController is not defined .

My test:

/* jasmine specs for controllers go here */
describe('PhoneCat controllers', function () {
    describe('PhoneListCtrl', function () {
        it('should create "phones" model with 3 phones', function () {
            var scope = {},
                ctrl = new PhoneListCtrl(scope);
            expect(scope.phones.length).toBe(3);
        });
    });
});

如果我将控制器更改为经典函数,则测试工作正常。

我错过了什么?

在你的测试中,你不应该"手工"创建控制器实例,而是让AngularJS使用$controller服务创建实例。这是必要的,因为AngularJS的DI系统需要有机会注入依赖项。

您的测试应该大致如下:

 beforeEach(module('App'));
 it('should create "phones" model with 3 phones', inject(function ($controller, $rootScope) {
    var ctrl = $controller('PhoneListCtrl', {$scope: $rootScope});   
    expect($rootScope.phones.length).toBe(3);
 }));

对于希望实例化一个新作用域并使用它的人:

    var ctrl = $scope.$new();
$controller('PhoneListCtrl', {$scope: ctrl});   
    expect(ctrl.phones.length).toBe(3);

最新更新