如何在 Angular JS 中使用 Jasmine 测试 NG 表单项目的有效性



我尝试用茉莉花对angularjs指令进行单元测试。我的指令包括在模糊事件上完成一个带有前导零的 id,然后检查这个 id 是否已经存在于 id 列表中(由 json 文件提供(。如何测试表单的有效性(id.$error.unique(提前感谢您的帮助!

该指令:

angular.module('bdd.directives').directive('bddUnique', function () {
    function formatIdentifier(id) {
        if (id) {
            var zeroes = '0000000000';
            var formattedId = zeroes.substring(0, zeroes.length - id.length) + id;
            return formattedId;
        }
        return '';
    }
    return {
        restrict : 'A',
        require : 'ngModel',
        link : function (scope, element, attrs, ctrl) {
            element.bind('blur', function (e) {
                ctrl.$setValidity('unique', true);
                if (ctrl && element.val()) {
                    var identifiers = scope.$eval(attrs.bddUnique);
                    var currentValue = formatIdentifier(element.val());
                    ctrl.$setViewValue(currentValue);
                    ctrl.$render();
                    var idFound = _.find(identifiers, {
                        id : currentValue
                    });
                    if (idFound !== undefined) {
                        ctrl.$setValidity('unique', false);
                    }
                }
                scope.$apply();
            });
        }
    }
});

单元测试

describe('uniqueDirective', function () {
    var mockCompile, mockScope;
    var changeInputValue;
    var htmlFragment = '<div ng-form name="myForm"><input type="text" ng-model="id" bdd-unique="identifiers"/>';
    htmlFragment += '<p id="errorMsg" ng-show="myForm.numero.$invalid">identifier already exist</p></div>';
    // / / / / load the myModule.directives module, which contains the directive
    beforeEach(module('myModule', function ($provide) {
        $provide.value('resolver', {
            identifiers : function () {
                return readJSON('app/assets/mocks/identifiers.json');
            }
        });
    }));
    beforeEach(inject(function (_$compile_, _$rootScope_, resolver) {
        mockCompile = _$compile_;
        mockScope = _$rootScope_.$new();
        mockScope.identifiers = resolver.identifiers();
         elem = angular.element(htmlFragment);
         template = mockCompile(elem)(mockScope);
         mockScope.$digest(); 
    }));
    it('id already exists', function () {

        var input = template.find('input'); 
        input.val('15);
        input.triggerHandler('blur');

        expect(mockScope.id).toBe('0000000015'); // OK
        // expect(myForm.numero.$error.unique.$valid).toBeFalsy();  //how to specify ???
    });
});

已解决

将 name="numero' 添加到 htmlFragment,这样它就变成了

 var htmlFragment = '<div ng-form name="myForm"><input type="text" 
    name='numero' ng-model="id" bdd-unique="identifiers"/>';

然后测试错误案例

var form = mockScope.myForm;
expect(form.numero.$error.unique).toBeTruthy();

测试正常情况

var form = mockScope.myForm;
expect(form.numero.$error.unique).toBeUndefined();

最新更新