0

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.

1 Answer 1

1

What you should do is to use the modelController $setViewValue(value) to trigger your parser pipeline. To get hold of the modelcontroller, you would have to wrap the dummy html in a form:

  $compile('<form name="form1"><input percent ng-model="someModel.Property" name='data'></input></form>')($rootScope);
  $rootScope.form1.data.$setViewValue('1a2b3')
  $rootScope.$digest();
  console.log($rootScope.someModel);
  expect($rootScope.someModel.Property).toEqual('123');

Can you give it a try.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.