我正在关注有关如何对控制器进行单元测试的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');
        });
    });
})

最佳答案

这是工作中的plunkr

回答Narek Mamikonyan时,您尚未在模块上注册控制器。

simulatorApp.controller('testController', testController);

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


homeController可能存在相同的问题

simulatorApp.controller('homeController', homeController);

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


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

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


如果您不这样做,则$ scope一旦缩小就不会相同,并且您的应用程序将无法运行。

关于javascript - 在Angular.js中对 Controller 进行单元测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28306802/

10-12 12:42
查看更多