【问题标题】:How to test function out of scope and this in AngularJS Unit Testing如何在AngularJS单元测试中测试超出范围的功能和this
【发布时间】:2015-11-28 07:05:24
【问题描述】:

我需要对特定控制器进行测试。

测试这个控制器没问题:

angular.module('app', []).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('app', []).controller('PasswordController', function PasswordController($scope) {


    var vm = this;
    vm.password = '';

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

我尝试使用以下代码测试控制器:

describe('Test', function () {

    beforeEach(module('app'));

    var MainCtrl, scope;

    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        MainCtrl = $controller('PasswordController', {
            $scope: scope
        });
    }));

    it('Should not throw Exception', function () {
        scope.password = 'abc';
        var call = function () {
            MainCtrl.grade();
        }
        expect(call).not.toThrow();
    });
});

但是我得到了这个错误:预期的函数不会抛出,但它抛出了 TypeError: 'undefined' is n ot 一个函数(评估 'MainCtrl.grade()')。

这个stackOverflow Question 帮助我将测试应用到“this”中的功能。但我想测试 $scope 和 'this' 之外的函数...

知道如何对这个控制器应用单元测试吗?

【问题讨论】:

    标签: angularjs unit-testing controller jasmine karma-jasmine


    【解决方案1】:

    等级方法未附加到控制器;

    vm.grade = grade;
    

    Working Plunkr

    【讨论】:

    • 我认为 OP 故意将方法保持为“私有”。仅仅为了测试而公开它对我来说听起来不对。
    • 如果你想直接测试它,它必须以某种方式暴露出来。如果它是从控制器内的另一个动作中调用的,则可以验证。例如,如果您在 vm.password 上有一个执行等级方法的观察者,您将能够验证强度属性是在摘要之后应该是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多