对使用 ngModel 的 Angular 指令进行单元测试

Unit Testing an Angular Directive that Uses ngModel

我目前正在为我一直在开发的应用程序编写单元测试,但我不确定如何处理这种情况。如何为 ngModel.$validate() 创建一个 spyOn 函数?

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)];

我正在尝试编写这样的测试:

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

  it('should', () => {

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

非常感谢任何帮助!

我没有为 $validate() 创建 spyOn 函数,而是通过使用表单控制器直接操作来测试 link 函数中 scope.$watch 的功能为指令传递什么。查看此测试:

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

    let password = 'nerfherder';

    let confirmPassword = 'nerfherder';

    it('should validate with matching passwords', () => {

        form.password.$setViewValue(password);

        form.confirmPassword.$setViewValue(confirmPassword);

        $rootScope.$digest();

        expect($rootScope.user.password)
            .toBe(password);

        expect($rootScope.user.confirmPassword)
            .toBe(confirmPassword);

        expect(form.password.$valid).toBe(true);
    });

    it('should not validate with passwords that do not match', () => {

        confirmPassword = 'badpassword';

        form.password.$setViewValue(password);

        form.confirmPassword.$setViewValue(confirmPassword);

        $rootScope.$digest();

        expect($rootScope.user.password)
            .toBe(password);

        expect($rootScope.user.confirmPassword)
            .toBeUndefined();

        expect(form.confirmPassword.$valid).toBe(false);
    });
});