Reputation: 379
I am new to Anuglar JS unit testing using jasmine, I have a directive that requires model. following is the code for the directive (it only append $ sign before provide number in a given model:
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;
});
}
};
}])
I have been looking into jamine I was able to test filters and controllers easily and also some of directives but this one reuiqres model so I am stuck at it any suggestions? highly grateful for your suggestions (in advance :) )
Best regards Sajid
Upvotes: 2
Views: 239
Reputation: 2882
You should probably write your test like this:
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
}));
Upvotes: 1