簡體   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