如何在AngularJS单元测试中测试超出范围的功能

前端之家收集整理的这篇文章主要介绍了如何在AngularJS单元测试中测试超出范围的功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要将测试应用于特定的控制器.

测试这个控制器是好的:

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',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’是n
一个函数(评估’MainCtrl.grade()’).

这个stackOverflow Question帮我在’this’里面运行测试.但我想测试$scope和’this’中的函数

任何想法如何将单元测试应用于此控制器?

解决方法

等级方法没有附加到控制器;

vm.grade = grade;

Working Plunkr

猜你在找的Angularjs相关文章