2014-05-13 115 views
2

我是新來Anuglar JS單元測試使用茉莉花,我有一個指令,需要模型。以下是該指令碼(只追加$符號之前,在給定的模型提供數量:AngularJS單元測試指令,需要模型(使用茉莉花)

directive('format', ['$filter', function ($filter) { 
    return { 
     require: '?ngModel', 
     link: function (scope, elem, attrs, ctrl) { 
      if (!ctrl) return; 

      ctrl.$formatters.unshift(function (value) { 
       //return '$' + $filter(attrs.format)(ctrl.$modelValue); 
       var num = $filter('currency')(ctrl.$modelValue); 
       return num.split('.')[0]; 
      }); 

      ctrl.$parsers.unshift(function (viewValue) { 
       var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, ''); 
       plainNumber = $filter('number')(plainNumber); 
       var inputVal = plainNumber.indexOf('$') < 0 ? '$' + plainNumber : plainNumber; 
       elem.val(inputVal); 
       return plainNumber; 
      }); 
     } 
    }; 
}]) 

我一直在尋找到jamine我能夠輕鬆地測試過濾器和控制器,還有一些指令,但是這一個reuiqres模式,使我停留在它的任何建議,非常感謝您的建議(提前:))

問候 Sajid

回答

1

你或許應該寫你的測試是這樣的:

it('tests this directive', inject(function($rootScope, $compile){ 
    var scope = $rootScope.$new(); 
    scope.myModelValue = 'something'; 
    var html = '<input format ng-model="myModelValue"></input>' 

    var element = $compile(html)(scope); 
    // I can't remember, but I think you need to call a scope.$apply() here 
    // element.val() will return formatted value from the $parsers 
    // Then element.val('something else') && scope.$apply() should change myModelValue from $formatters 
})); 
+0

謝謝你我的回覆我要試一試 – Sajid