-1

I tried to write test case for directive, But i can't write. So, guys can u share the correct test case with explanation for given directive.js.

myapp.directive('number', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attr, form) {    
            element.bind('input', function(e) {
                $(this).val($(this).val().replace(/[^0-9 ]/gi, ''));
            });
        }
    }
});

This directive should return numbers only.

1 Answer 1

0

I found the answer. I posted my answer here,

describe('number', function() {
  var scope, element, $compile;
  beforeEach(module('myapp'));

  beforeEach(inject(function(_$compile_, $rootScope) {
    scope = $rootScope.$new();
    $compile =_$compile_;
    scope.testInput = "";
    element = angular.element('<input number ng-model="testInput">');
  }));

  var triggerKeyDown = function () {
    var e = $.Event("input");
    $(element).trigger(e);
  };

  it('should accept number input only', function() {
    $compile(element)(scope);
    scope.testInput = '1';
    scope.$digest();
    triggerKeyDown();
    expect(scope.testInput).toBe('1');
  }); 
});

This code works for me.

Not the answer you're looking for? Browse other questions tagged or ask your own question.