繁体   English   中英

Karma单元测试'undefined'不是函数错误

[英]Karma unit test 'undefined' is not a function error

我有一个自定义指令,用于检查两个输入字段中的值是否彼此相等(重复密码),我想测试。 它工作正常,但测试失败并出现此错误:

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正在加载jqLit​​e而不是jQuery,它没有add功能。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM