单元测试Angular.js中的控制器

时间:2015-02-03 19:08:00

标签: javascript angularjs unit-testing karma-jasmine

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

2 个答案:

答案 0 :(得分:1)

这是一个有效的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 一旦缩小就不会再一样了,你的应用程序也无法工作。

答案 1 :(得分:0)

您没有在模块中定义控制器

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