Simulating user input for TDD JavaScript

元气小坏坏 提交于 2019-11-28 04:03:31

问题


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.

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');

Without the correct code, this test should fail because the input should have a value of 'testd' (68 is the character code for 'd').

Does anyone know any methods or libraries to simulate real browser UI events?


回答1:


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.




回答2:


You probably want to try using Selenium: http://seleniumhq.org/

Here's a decent overview: http://blog.frontendforce.com/2010/05/unit-testing-in-javascript-selenium/




回答3:


I believe YUI had some code to do that. Download their code and take a look. I believe it is called simulate.js or something similar. Alternatively you can look at how selenium does it.




回答4:


Here's a repo that seems to be kept quite well up to date: https://github.com/mmonteleone/jquery.autotype



来源:https://stackoverflow.com/questions/6770662/simulating-user-input-for-tdd-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!