Unit Testing an Angular Directive that Uses ngModel

时间:2015-07-28 22:42:40

标签: angularjs unit-testing jasmine ecmascript-6 karma-jasmine

I am currently writing unit tests for an app I have been working on, but I am unsure of how to handle this case. How does one create a spyOn function for ngModel.$validate()?

let moduleName = 'compareTo';

// ## Directive Definition
class compareTo {

  constructor() {

    this.restrict = 'EA';
    this.require = 'ngModel';
    this.scope = { otherModelValue : '=compareTo' };
  }

  // ### Optional Link Function
  link (scope, elem, attrs, ngModel) {

    ngModel.$validators.compareTo = (modelValue) => {

      return modelValue == scope.otherModelValue;
    };

    scope.$watch('otherModelValue', () => {

      // I am trying to spy on this function call.
      ngModel.$validate();
    });
  }
}

export default [moduleName, directiveFactory(compareTo)];

I am trying to write a test like so:

describe('link function', () => {

  it('should', () => {

    spyOn(/* not sure what should go here? */, '$validate');
  });
});

Any help is much appreciated!

1 个答案:

答案 0 :(得分:0)

Rather than create a table.column([column number]).data().filter(function (value, index) {}); function for spyOn, I went about testing the functionality of $validate() in the scope.$watch function by using the form controller to directly manipulate what to pass for directives. See this test:

link