使用 karma 测试不使用 $scope 的控制器

Testing a controller not using $scope using karma

我按照 docs.angularjs.org 上的说明使用 karma 测试了控制器,它运行良好。 但是我想知道是否可以测试不使用 $scope 的控制器?

测试此控制器正常:

angular.module('starter.controllers')
.controller('PasswordController', function PasswordController($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';
        }
    };
});

但我想测试一下:

angular.module('starter.controllers')
.controller('PasswordController', function PasswordController()
{
    var myController = this;
    myController.password = '';
    myController.grade = function()
    {
        var size = myController.password.length;
        if (size > 8) {
            myController.strength = 'strong';
        } else if (size > 3) {
            myController.strength = 'medium';
        } else {
            myController.strength = 'weak';
        }
    };
});

测试代码如下:

describe('PasswordController', function()
{
    beforeEach(module('starter.controllers'));

    var $controller;

    beforeEach(inject(function(_$controller_){
        $controller = _$controller_;
    }));

    describe('$scope.grade', function() {
        var $scope, controller;

        beforeEach(function() {
            $scope = {};
            //This line doesn't work with the second controller
            controller = $controller('PasswordController', { $scope: $scope});
        });

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

这应该有效:

describe('PasswordController', function()
{
    beforeEach(module('starter.controllers'));

    var $controller;

    beforeEach(inject(function(_$controller_){
        $controller = _$controller_;
    }));

    describe('$scope.grade', function() {
        var controller;

        beforeEach(function() {
            controller = $controller('PasswordController', {});
        });

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