在 Angular.js 中对控制器进行单元测试

Unit Testing a Controller in Angular.js

我正在学习有关如何对控制器进行单元测试的 Angular 教程。我正在使用 Karma 和 Jasmine 进行测试。当我 运行 测试时,我得到

Error: [ng:areq] Argument 'testController' is not a function, got undefined

关于如何在 test.js 中加载 testController 有什么想法吗?下面的代码。谢谢!

<!-- app.js --> 

var simulatorApp = angular.module('simulatorApp', ['ngRoute', 'ngResource', 'ngCookies'],

simulatorApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {templateUrl: '/angular/views/home.html', controller: homeController})
        .when('/test', {templateUrl: '/angular/views/test.html', controller: testController})
        .otherwise({redirectTo: '/'});
}]);

<!-- testController.js -->

function testController($scope) {
    $scope.password = '';
    $scope.grade = function () {
        var size = $scope.password.length;
        if (size > 8) {
            $scope.strength = 'strong';
        } else if (size > 3) {
            $scope.strength = 'medium';
        } else {
            $scope.strength = 'weak';
        }
    };
}

<!-- test.js -->
describe('testController', function() {
    beforeEach(module('simulatorApp'));

    var $controller;

    beforeEach(inject(function (_$controller_) {
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $controller = _$controller_;
    }));

    describe('$scope.grade', function () {
        it('sets the strength to "strong" if the password length is >8 chars', function () {
            var $scope = {};
            var controller = $controller('testController', {$scope: $scope});
            $scope.password = 'longerthaneightchars';
            $scope.grade();
            expect($scope.strength).toEqual('strong');
        });
    });
})

您没有在模块

中定义您的控制器
simulatorApp.controller('testController', function testController($scope) {
    $scope.password = '';
    $scope.grade = function () {
        var size = $scope.password.length;
        if (size > 8) {
            $scope.strength = 'strong';
        } else if (size > 3) {
            $scope.strength = 'medium';
        } else {
            $scope.strength = 'weak';
        }
    };
})

这是一个有效的 plunkr

正如回答的那样,您还没有在模块上注册控制器。

simulatorApp.controller('testController', testController);

function testController($scope) {
    ...
};

homeController

可能有同样的问题
simulatorApp.controller('homeController', homeController);

function homeController($scope) {
    ...
};

此外,您应该尝试像这样声明您的控制器,因为如果您对 javascript 文件进行缩小,它不会爆炸

simulatorApp.controller('testController', ['$scope', testController]);

如果不这样做,$scope 缩小后将不一样,您的应用将无法运行。