模拟TDD JavaScript的用户输入 [英] Simulating user input for TDD JavaScript
问题描述
我发现使用jQuery或本机元素触发器函数模拟实际用户事件越来越困难。例如,如果您有文本输入而您不希望用户能够添加字符,则可以使用jQuery调用 e.preventDefault()
keydown
事件上的规范化事件对象。但是,没有办法以编程方式验证此测试方案。
I'm finding it increasingly difficult to simulate actual user events using jQuery or native element trigger functions. For example, if you have a text input and you don't want the user to be able to add a character, you can call e.preventDefault()
with the jQuery-normalised event object on the keydown
event. However, there is no way to programatically verify this test scenario.
即使没有调用 preventDefault
因为jQuery keydown触发器不是真实事件。
The following test passes even without the call to preventDefault
because the jQuery keydown trigger isn't a "real" event.
input.val('test').trigger(jQuery.Event({
which: 68
});
expect(input).toHaveValue('test');
如果没有正确的代码,此测试应该失败,因为输入的值应为'testd'(68是'd'的字符代码)。
Without the correct code, this test should fail because the input should have a value of 'testd' (68 is the character code for 'd').
有没有人知道任何模拟真实浏览器UI事件的方法或库?
Does anyone know any methods or libraries to simulate real browser UI events?
推荐答案
模拟真实事件非常复杂。您必须首先确定需要哪种类型的事件,然后使用 document.createEvent
。然后将不同的 init * Event
调用到initi最后,使用 element.dispatchEvent
将事件发送到目标对象。
Simulate real event is quite complicated. You must first determine which type of event you need and create it with document.createEvent
. Then call different init*Event
to initialize the event object. Finally, use element.dispatchEvent
to dispatch the event to the target object.
这篇关于模拟TDD JavaScript的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!