AngularJS Karma 测试中的 jQuery 触发事件

时间:2023-04-30
本文介绍了AngularJS Karma 测试中的 jQuery 触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试测试我正在编写的新指令.但是,我似乎无法在 Karma/Jasmine 中使用 jQuery 触发 keydown 事件.

I'm trying to test a new directive I'm writing. However, I can't seem to get the keydown event to trigger with jQuery inside Karma/Jasmine.

这是一个简化版的测试:

Here is a simplified version of the test :

'use strict';

describe('', function() {

  var $compile;
  var $scope;

  beforeEach(inject(function(_$compile_, _$rootScope_) {
    $compile = _$compile_;
    $scope = _$rootScope_.$new();
  }));

  describe('Getting Trigger To Work', function() {

    it('Should Trigger a KeyDown Event', function() {

      var el = $compile('<form name="testing"><input id="field1" name="testfield" ng-model="result" type="text" ng-minlength="5" ng-maxlength="50"/></form>')($scope);
      console.log(el);

      var inputEl = el.find('input');
      console.log(inputEl);

      var e = $.Event('keydown');
      e.which = 65;

      inputEl.trigger(e);

    });

  });

});

我的 karma 配置包括 AngularJS 和 jQuery.这是该部分:

My karma config includes AngularJS and jQuery. Here's that section:

//
files: [
  'lib/angular.js',
  'lib/angular-mocks.js',
  'lib/jquery-1.10.2.min.js',
  'test/**/*Spec.js'
],

当我运行测试时,我得到一个错误,我的输入元素没有触发方法:

When I run the test, I get an error that my input element has no trigger method :

INFO [watcher]: Changed file "/Volumes/Macintosh HD/dev_libraries/val-on-timeout/test/valOnTimeoutSpec.js".
LOG: Object{0: <form name="testing" class="ng-scope ng-pristine ng-valid"><input id="field1" name="testfield" ng-model="result" type="text" ng-minlength="5" ng-maxlength="50" class="ng-pristine ng-valid"></form>, length: 1}
LOG: Object{0: <input id="field1" name="testfield" ng-model="result" type="text" ng-minlength="5" ng-maxlength="50" class="ng-pristine ng-valid">, length: 1}
Chrome 32.0.1700 (Mac OS X 10.8.5)  testing valOnTimeout Should load FAILED
    TypeError: Object [object Object] has no method 'trigger'
        at null.<anonymous> (/Volumes/Macintosh HD/dev_libraries/val-on-timeout/test/valOnTimeoutSpec.js:79:21)
Chrome 32.0.1700 (Mac OS X 10.8.5): Executed 1 of 1 (1 FAILED) ERROR (0.327 secs / 0.033 secs)

一开始,你可能会认为 jQuery 是不包括在内的.但是,它包括在内.如果不是,则测试将在 $.Event 处失败.

At first, you may think that jQuery is not included. However, it is included. If it were not, the test would fail at $.Event.

关于让 keydown 事件对输入起作用的建议?

Suggestions on getting the keydown event to work on the input?

推荐答案

我希望这可行

  var e = $.Event('keydown');
  e.which = 65;

  $(inputEl).trigger(e); // convert inputEl into a jQuery object first
  // OR
  angular.element(inputEl).triggerHandler(e); // angular.element uses triggerHandler instead of trigger to trigger events

这篇关于AngularJS Karma 测试中的 jQuery 触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:AngularJs Jasmine 单元测试中的 $httpBackend 下一篇:Sinon 似乎没有监视事件处理程序回调

相关文章

最新文章