2017-05-10 2 views
0

私はジャスミンでangularjs命令をユニットテストしようとします。 私のディレクティブは、ぼかしイベントに対して、先行するゼロを持つidを完了し、このidがすでにidのリスト(jsonファイルによって提供されている)に存在するかどうかをチェックします。 フォームの有効性をテストする方法(id。$ error.unique) おかげさまで、ありがとうございました!角度jsでjasmineでng-formアイテムの有効性をテストする方法

ディレクティブ:

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 ??? 

    }); 

}); 

答えて

0

はhtmlFragmentに名前= "NUMERO」を追加

を解決したので、それは

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).toBeUndefined(); 
通常の場合をテストするために、エラーケース

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

をテストする3210

関連する問題