My directive looks like this (removes non-digits from input):
'use strict';
angular.module('fooApp')
.directive('percent', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
// get rid of non-number data
var transformedInput = text.replace(/[^0-9]/g, '');
if(transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
}
my test looks like this:
'use strict';
describe('Directive: percent', function () {
var $compile;
var $rootScope;
beforeEach(module('fooApp'));
beforeEach(inject(function(_$compile_, _$rootScope_){
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
it('Removes non-digits', function () {
$compile('<input percent ng-model="someModel.Property" value="1a2b3"></input>')($rootScope);
$rootScope.$digest();
console.log($rootScope.someModel);
expect($rootScope.someModel.Property).toEqual('123');
});
});
However I can see in the log:
LOG: undefined
So it sounds like someModel is not set => test fails.
Not sure what's wrong with my directive. If I test manually: input non-digits in HTML page, these are not shown (are ignored).
What would be the proper way to test that?
I suspect, that my directive is not modifying stuff once data don't come from user but are set via value. Not sure however how to change that.