因果报应单元测试'未定义'不是函数错误

Karma unit test 'undefined' is not a function error

本文关键字:函数 错误 因果报应 未定义 单元测试      更新时间:2024-03-20

我有一个自定义指令,用于检查我想要测试的两个输入字段中的值是否相等(重复密码)。它运行良好,但测试失败,出现以下错误:

TypeError: 'undefined' is not a function (evaluating 'element.add(tween)')

指令非常简单明了:

angular.module('fmAppApp')
.directive('valueMatch', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function postLink(scope, element, attrs, ctrl) {
        var tween = '#' + attrs.valueMatch;
        element.add(tween).on('keyup', function () {
          scope.$apply(function () {
            var v = element.val() === $(tween).val();
            ctrl.$setValidity('valueMatch', v);
          });
        });
   }
 };

});

这是规格:

describe('Directive: valueMatch', function () {
  // load the directive's module
  beforeEach(module('fmAppApp'));
  var element, origElement,
    scope;
  beforeEach(inject(function ($rootScope) {
   scope = $rootScope.$new();
  }));
  it('should set change validity state of element depending on value of another element',
    inject(function ($compile) {
      origElement = $compile('<input id="orig">')(scope);
      element = $compile('<input value-match="orig" ng-model="repeat">')(scope);
      scope.$digest();
      expect(element.$valid).toBe(true);
      origElement.val('12345');
      scope.$digest();
      expect(element.$valid).toBe(false);
      element.val('12345');
      expect(element.$valid).toBe(true);
 }));
});

显然add()是未定义的,对吧?但为什么呢?

我相信在单元测试的情况下,Angular加载的是jqLite,而不是jQuery,它没有add函数。

要么使用此处描述的jqlite兼容函数之一https://code.angularjs.org/1.2.9/docs/api/angular.element

或者在你的测试中也包括jQuery,在karma配置中。