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

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

问题描述

我要进行单元测试,模拟一个占位符,其中输入值仅在KEYUP /关闭事件清除指令。

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/项目位置:<一href=\"https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/test/typeahead.spec.js\">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

免责声明:让我们的是precise这里:我没有使用jQuery与AngularJS提倡!我只是说这是编写测试与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.

为了使上述code工作的没有的jQuery的,变化:

To make the above code work without jQuery, change:

$.Event('keydown')

angular.element.Event('keydown')

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

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