如何在 angularjs 单元测试中触发 keyup/keydown 事件? [英] How do I trigger a keyup/keydown event in an angularjs unit test?

查看:33
本文介绍了如何在 angularjs 单元测试中触发 keyup/keydown 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对一个模拟占位符的指令进行单元测试,其中输入值仅在 keyup/down 事件中被清除.

I want to unit test a directive that emulates a placeholder, where the input value is cleared only on keyup/down events.

推荐答案

您需要以编程方式创建一个事件并触发它.为此,包括用于单元测试的 jQuery 非常有用.例如,您可以编写这样一个简单的实用程序:

You need to create an event programatically and trigger it. To do so including jQuery for unit tests is quite useful. For example, you could write a simple utility like this:

  var triggerKeyDown = function (element, keyCode) {
    var e = $.Event("keydown");
    e.which = keyCode;
    element.trigger(e);
  };

然后像这样在单元测试中使用它:

and then use it in your unit test like so:

triggerKeyDown(element, 13);

您可以在 http://angular-ui.github.io/中看到这种技术的实际应用bootstrap/ 项目在这里:https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/test/typeahead.spec.js

You can see this technique in action in the http://angular-ui.github.io/bootstrap/ project here: https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/test/typeahead.spec.js

免责声明:让我们准确地说:我不提倡在 AngularJS 中使用 jQuery!我只是说它是一个有用的 DOM 操作实用程序,用于编写与 DOM 交互的测试.

Disclaimer: let's be precise here: I'm not advocating using jQuery with AngularJS! I'm just saying that it is a useful DOM manipulation utility for writing tests interacting with the DOM.

要使上述代码在没有 jQuery的情况下工作,请更改:

To make the above code work without jQuery, change:

$.Event('keydown')

到:

angular.element.Event('keydown')

这篇关于如何在 angularjs 单元测试中触发 keyup/keydown 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆