AngularJS单元测试:如何为范围函数编写单元测试?

时间:2016-10-18 17:30:16

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

角度和单位测试的新手,我的控制器中有一个功能如下:

function TermList($scope, $http, $q, $timeout, $modal, uiGridConstants, uiGridGroupingConstants, storedValue, sendEmail, getUser) {


    $scope.greeting = "hello";
    $scope.sum = function sum() {
        $scope.z = $scope.x + $scope.y;
    };

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

}

我需要为我的范围函数编写单元,我编写了以下测试用例:

describe('routerApp', function () {
    var scope,
    controller;
    beforeEach(function () {
        module('routerApp');
    });

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

        it('sets the name', function () {
            expect(scope.greeting).toEqual('hello');
        });
    });
});

我运行单元测试时出现以下错误:

   TypeError: Cannot read property 'greeting' of undefined

1 个答案:

答案 0 :(得分:-1)

您的inject参数看起来很可疑;我并不完全相信他们会注入任何东西。

如果要保留参数的名称,则可以使用下划线为每个参数添加前缀和后缀。

beforeEach(inject(function (_$rootScope_, _$controller_) {
    scope = _$rootScope_.$new();
    controller = _$controller_('TermList', {
        '$scope': scope
    });
}));