UNPKG

2.81 kBMarkdownView Raw
1# simulant.js
2
3**Simulated DOM events for automated testing**
4
5## What's this for?
6
7Sometimes you need to create fake DOM events so that you can test the parts of your app or library that depend on user input. But doing so is a royal pain in the arse:
8
9```js
10// WITHOUT SIMULANT.JS
11try {
12 // DOM Level 3
13 event = new MouseEvent( 'mousemove', {
14 bubbles: true,
15 cancelable: true,
16 relatedTarget: previousNode
17 });
18
19 node.dispatchEvent( event );
20}
21
22catch ( err ) {
23 if ( document.createEvent ) {
24 // DOM Level 2
25 event = document.createEvent( 'MouseEvents' );
26 event.initMouseEvent( 'mousemove', true, true, window, null, 0, 0, 0, 0, '', false, false, false, false, 0, previousNode );
27
28 node.dispatchEvent( event );
29 }
30
31 else {
32 // IE8 and below
33 event = document.createEventObject();
34 event.relatedTarget = previousNode;
35
36 node.fireEvent( 'onmousemove', event );
37 }
38}
39
40
41// WITH SIMULANT.JS
42simulant.fire( node, 'mousemove', { relatedTarget: previousNode });
43```
44
45Simulant was created to make automated testing of [Ractive.js](https://github.com/ractivejs/ractive) across different browsers easier.
46
47
48## Why not just use jQuery?
49
50In some cases you can. But events created with `$(element).trigger('click')`, for example, won't trigger handlers bound using `element.addEventListener('click', handler)` in many situations, such as when you're doing automated tests with [PhantomJS](http://phantomjs.org/).
51
52Simulant uses native DOM events, not fake events, so its behaviour is more predictable.
53
54
55## Installation
56
57```bash
58npm install simulant
59```
60
61
62## Usage
63
64```js
65// Create a simulated event
66event = simulant( 'click' );
67
68// Create a simulated event with parameters, e.g. a middle-click
69event = simulant( 'click', { button: 1, which: 2 });
70
71// Fire a previously created event
72target = document.getElementById( 'target' );
73simulant.fire( target, event );
74
75// Create an event and fire it immediately
76simulant.fire( target, 'click' );
77simulant.fire( target, 'click', { button: 1, which: 2 });
78
79// Polyfill addEventListener in old browsers
80if ( !window.addEventListener ) {
81 simulant.polyfill();
82}
83```
84
85
86## Limitations
87
88Normally, events have side-effects - a click in a text input will focus it, a mouseover of an element will trigger its hover state, and so on. When creating events programmatically, these side-effects don't happen - so your tests shouldn't expect them to. For example you shouldn't fire simulated keypress events at an input element and expect its value to change accordingly.
89
90There are exceptions - a click event on a checkbox input will cause a secondary change event to be fired, for example.
91
92
93## License
94
95Copyright (c) 2013-14 [Rich Harris](http://rich-harris.co.uk) ([@rich_harris](http://twitter.com/rich_harris)).
96Released under an MIT license.