使用karma

时间:2015-05-22 16:10:31

标签: angularjs unit-testing scope karma-jasmine controllers

我按照docs.angularjs.org上的说明来测试一个带有业力的控制器,它完全正常工作。 但是我想知道是否可以测试不使用$ 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');
        });
    });
});

1 个答案:

答案 0 :(得分:3)

这应该有效:

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