@testing-library/user-event 13.1.7 → 13.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,16 +1,23 @@
1
1
  <div align="center">
2
- <h1>@testing-library/user-event</h1>
2
+ <h1>user-event</h1>
3
3
 
4
4
  <a href="https://www.joypixels.com/profiles/emoji/1f415">
5
5
  <img
6
6
  height="80"
7
7
  width="80"
8
8
  alt="dog"
9
- src="https://raw.githubusercontent.com/testing-library/user-event/master/other/dog.png"
9
+ src="https://raw.githubusercontent.com/testing-library/user-event/main/other/dog.png"
10
10
  />
11
11
  </a>
12
12
 
13
13
  <p>Fire events the same way the user does</p>
14
+
15
+ <br />
16
+
17
+ [**Read The Docs**](https://testing-library.com/docs/ecosystem-user-event) |
18
+ [Edit the docs](https://github.com/testing-library/testing-library-docs)
19
+
20
+ <br />
14
21
  </div>
15
22
 
16
23
  ---
@@ -24,619 +31,76 @@
24
31
  [![All Contributors][all-contributors-badge]](#contributors)
25
32
  [![PRs Welcome][prs-badge]][prs]
26
33
  [![Code of Conduct][coc-badge]][coc]
27
- <!-- prettier-ignore-end -->
28
-
29
- ## The problem
30
-
31
- From
32
- [testing-library/dom-testing-library#107](https://github.com/testing-library/dom-testing-library/issues/107):
33
-
34
- > [...] it is becoming apparent the need to express user actions on a web page
35
- > using a higher-level abstraction than `fireEvent`
36
-
37
- ## The solution
34
+ [![Discord][discord-badge]][discord]
38
35
 
39
- `user-event` tries to simulate the real events that would happen in the browser
40
- as the user interacts with it. For example `userEvent.click(checkbox)` would
41
- change the state of the checkbox.
42
-
43
- **The library is still a work in progress and any help is appreciated.**
36
+ [![Watch on GitHub][github-watch-badge]][github-watch]
37
+ [![Star on GitHub][github-star-badge]][github-star]
38
+ [![Tweet][twitter-badge]][twitter]
39
+ <!-- prettier-ignore-end -->
44
40
 
45
41
  ## Table of Contents
46
42
 
47
43
  <!-- START doctoc generated TOC please keep comment here to allow auto update -->
48
44
  <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
49
45
 
46
+ - [The problem](#the-problem)
47
+ - [The solution](#the-solution)
50
48
  - [Installation](#installation)
51
- - [API](#api)
52
- - [`click(element, eventInit, options)`](#clickelement-eventinit-options)
53
- - [`dblClick(element, eventInit, options)`](#dblclickelement-eventinit-options)
54
- - [`type(element, text, [options])`](#typeelement-text-options)
55
- - [`keyboard(text, options)`](#keyboardtext-options)
56
- - [`upload(element, file, [{ clickInit, changeInit }], [options])`](#uploadelement-file--clickinit-changeinit--options)
57
- - [`clear(element)`](#clearelement)
58
- - [`selectOptions(element, values)`](#selectoptionselement-values)
59
- - [`deselectOptions(element, values)`](#deselectoptionselement-values)
60
- - [`tab({shift, focusTrap})`](#tabshift-focustrap)
61
- - [`hover(element)`](#hoverelement)
62
- - [`unhover(element)`](#unhoverelement)
63
- - [`paste(element, text, eventInit, options)`](#pasteelement-text-eventinit-options)
64
- - [`specialChars`](#specialchars)
49
+ - [Docs](#docs)
50
+ - [Known limitations](#known-limitations)
65
51
  - [Issues](#issues)
66
52
  - [🐛 Bugs](#-bugs)
67
53
  - [💡 Feature Requests](#-feature-requests)
68
- - [Contributors ✨](#contributors-)
54
+ - [❓ Questions](#-questions)
55
+ - [Contributors](#contributors)
69
56
  - [LICENSE](#license)
70
57
 
71
58
  <!-- END doctoc generated TOC please keep comment here to allow auto update -->
72
59
 
73
- ## Installation
74
-
75
- With NPM:
76
-
77
- ```sh
78
- npm install @testing-library/user-event @testing-library/dom --save-dev
79
- ```
80
-
81
- With Yarn:
82
-
83
- ```sh
84
- yarn add @testing-library/user-event @testing-library/dom --dev
85
- ```
86
-
87
- Now simply import it in your tests:
88
-
89
- ```js
90
- import userEvent from '@testing-library/user-event'
91
-
92
- // or
93
-
94
- const {default: userEvent} = require('@testing-library/user-event')
95
- ```
96
-
97
- ## API
98
-
99
- Note: All userEvent methods are synchronous with one exception: when `delay`
100
- with `userEvent.type` as described below). We also discourage using `userEvent`
101
- inside `before/after` blocks at all, for important reasons described in
102
- ["Avoid Nesting When You're Testing"](https://kentcdodds.com/blog/avoid-nesting-when-youre-testing).
103
-
104
- ### `click(element, eventInit, options)`
105
-
106
- Clicks `element`, depending on what `element` is it can have different side
107
- effects.
108
-
109
- ```jsx
110
- import React from 'react'
111
- import {render, screen} from '@testing-library/react'
112
- import userEvent from '@testing-library/user-event'
113
-
114
- test('click', () => {
115
- render(
116
- <div>
117
- <label htmlFor="checkbox">Check</label>
118
- <input id="checkbox" type="checkbox" />
119
- </div>,
120
- )
121
-
122
- userEvent.click(screen.getByText('Check'))
123
- expect(screen.getByLabelText('Check')).toBeChecked()
124
- })
125
- ```
126
-
127
- You can also ctrlClick / shiftClick etc with
128
-
129
- ```js
130
- userEvent.click(elem, {ctrlKey: true, shiftKey: true})
131
- ```
132
-
133
- See the
134
- [`MouseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
135
- constructor documentation for more options.
136
-
137
- Note that `click` will trigger hover events before clicking. To disable this,
138
- set the `skipHover` option to `true`. Also note that trying to click an element
139
- with `pointer-events` being set to `"none"` (i.e. unclickable) will throw an error.
140
-
141
- ### `dblClick(element, eventInit, options)`
142
-
143
- Clicks `element` twice, depending on what `element` is it can have different
144
- side effects.
145
-
146
- ```jsx
147
- import React from 'react'
148
- import {render, screen} from '@testing-library/react'
149
- import userEvent from '@testing-library/user-event'
150
-
151
- test('double click', () => {
152
- const onChange = jest.fn()
153
- render(<input type="checkbox" onChange={onChange} />)
154
- const checkbox = screen.getByRole('checkbox')
155
- userEvent.dblClick(checkbox)
156
- expect(onChange).toHaveBeenCalledTimes(2)
157
- expect(checkbox).not.toBeChecked()
158
- })
159
- ```
160
-
161
- ### `type(element, text, [options])`
162
-
163
- Writes `text` inside an `<input>` or a `<textarea>`.
164
-
165
- ```jsx
166
- import React from 'react'
167
- import {render, screen} from '@testing-library/react'
168
- import userEvent from '@testing-library/user-event'
169
-
170
- test('type', () => {
171
- render(<textarea />)
172
-
173
- userEvent.type(screen.getByRole('textbox'), 'Hello,{enter}World!')
174
- expect(screen.getByRole('textbox')).toHaveValue('Hello,\nWorld!')
175
- })
176
- ```
177
-
178
- `options.delay` is the number of milliseconds that pass between two characters
179
- are typed. By default it's 0. You can use this option if your component has a
180
- different behavior for fast or slow users. If you do this, you need to make sure
181
- to `await`!
182
-
183
- `type` will click the element before typing. To disable this, set the
184
- `skipClick` option to `true`.
185
-
186
- #### Special characters
187
-
188
- The following special character strings are supported:
189
-
190
- | Text string | Key | Modifier | Notes |
191
- | -------------- | ---------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
192
- | `{enter}` | Enter | N/A | Will insert a newline character (`<textarea />` only). |
193
- | `{space}` | `' '` | N/A | |
194
- | `{esc}` | Escape | N/A | |
195
- | `{backspace}` | Backspace | N/A | Will delete the previous character (or the characters within the `selectedRange`, see example below). |
196
- | `{del}` | Delete | N/A | Will delete the next character (or the characters within the `selectedRange`, see example below) |
197
- | `{selectall}` | N/A | N/A | Selects all the text of the element. Note that this will only work for elements that support selection ranges (so, not `email`, `password`, `number`, among others) |
198
- | `{arrowleft}` | ArrowLeft | N/A | |
199
- | `{arrowright}` | ArrowRight | N/A | |
200
- | `{arrowup}` | ArrowUp | N/A | |
201
- | `{arrowdown}` | ArrowDown | N/A | |
202
- | `{home}` | Home | N/A | |
203
- | `{end}` | End | N/A | |
204
- | `{shift}` | Shift | `shiftKey` | Does **not** capitalize following characters. |
205
- | `{ctrl}` | Control | `ctrlKey` | |
206
- | `{alt}` | Alt | `altKey` | |
207
- | `{meta}` | OS | `metaKey` | |
208
- | `{capslock}` | CapsLock | `modifierCapsLock` | Fires both keydown and keyup when used (simulates a user clicking their "Caps Lock" button to enable caps lock). |
209
-
210
- > **A note about modifiers:** Modifier keys (`{shift}`, `{ctrl}`, `{alt}`,
211
- > `{meta}`) will activate their corresponding event modifiers for the duration
212
- > of type command or until they are closed (via `{/shift}`, `{/ctrl}`, etc.). If
213
- > they are not closed explicitly, then events will be fired to close them
214
- > automatically (to disable this, set the `skipAutoClose` option to `true`).
215
-
216
- <!-- space out these notes -->
217
-
218
- > We take the same
219
- > [stance as Cypress](https://docs.cypress.io/api/commands/type.html#Modifiers)
220
- > in that we do not simulate the behavior that happens with modifier key
221
- > combinations as different operating systems function differently in this
222
- > regard.
223
-
224
- An example of an usage with a selection range:
225
-
226
- ```jsx
227
- import React from 'react'
228
- import {render, screen} from '@testing-library/react'
229
- import userEvent from '@testing-library/user-event'
230
-
231
- test('delete characters within the selectedRange', () => {
232
- render(
233
- <div>
234
- <label htmlFor="my-input">Example:</label>
235
- <input id="my-input" type="text" value="This is a bad example" />
236
- </div>,
237
- )
238
- const input = screen.getByLabelText(/example/i)
239
- input.setSelectionRange(10, 13)
240
- userEvent.type(input, '{backspace}good')
241
-
242
- expect(input).toHaveValue('This is a good example')
243
- })
244
- ```
245
-
246
- #### <input type="time" /> support
247
-
248
- The following is an example of usage of this library with
249
- `<input type="time" />`
250
-
251
- ```jsx
252
- import React from 'react'
253
- import {render, screen} from '@testing-library/react'
254
- import userEvent from '@testing-library/user-event'
255
-
256
- test('types into the input', () => {
257
- render(
258
- <>
259
- <label for="time">Enter a time</label>
260
- <input type="time" id="time" />
261
- </>,
262
- )
263
- const input = screen.getByLabelText(/enter a time/i)
264
- userEvent.type(input, '13:58')
265
- expect(input.value).toBe('13:58')
266
- })
267
- ```
268
-
269
- ### `keyboard(text, options)`
270
-
271
- Simulates the keyboard events described by `text`. This is similar to
272
- `userEvent.type()` but without any clicking or changing the selection range.
273
-
274
- > You should use `userEvent.keyboard` if you want to just simulate pressing
275
- > buttons on the keyboard. You should use `userEvent.type` if you just want to
276
- > conveniently insert some text into an input field or textarea.
277
-
278
- Keystrokes can be described:
279
-
280
- - Per printable character
281
- ```js
282
- userEvent.keyboard('foo') // translates to: f, o, o
283
- ```
284
- The brackets `{` and `[` are used as special character and can be referenced
285
- by doubling them.
286
- ```js
287
- userEvent.keyboard('{{a[[') // translates to: {, a, [
288
- ```
289
- - Per
290
- [KeyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
291
- (only supports alphanumeric values of `key`)
292
- ```js
293
- userEvent.keyboard('{Shift}{f}{o}{o}') // translates to: Shift, f, o, o
294
- ```
295
- This does not keep any key pressed. So `Shift` will be lifted before pressing
296
- `f`.
297
- - Per
298
- [KeyboardEvent.code](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code)
299
- ```js
300
- userEvent.keyboard('[ShiftLeft][KeyF][KeyO][KeyO]') // translates to: Shift, f, o, o
301
- ```
302
- - Per legacy `userEvent.type` modifier/specialChar The modifiers like `{shift}`
303
- (note the lowercase) will automatically be kept pressed, just like before. You
304
- can cancel this behavior by adding a `/` to the end of the descriptor.
305
- ```js
306
- userEvent.keyboard('{shift}{ctrl/}a{/shift}') // translates to: Shift(down), Control(down+up), a, Shift(up)
307
- ```
308
-
309
- Keys can be kept pressed by adding a `>` to the end of the descriptor - and
310
- lifted by adding a `/` to the beginning of the descriptor:
311
-
312
- ```js
313
- userEvent.keyboard('{Shift>}A{/Shift}') // translates to: Shift(down), A, Shift(up)
314
- ```
315
-
316
- `userEvent.keyboard` returns a keyboard state that can be used to continue
317
- keyboard operations.
318
-
319
- ```js
320
- const keyboardState = userEvent.keyboard('[ControlLeft>]') // keydown [ControlLeft]
321
- // ... inspect some changes ...
322
- userEvent.keyboard('a', {keyboardState}) // press [KeyA] with active ctrlKey modifier
323
- ```
324
-
325
- The mapping of `key` to `code` is performed by a
326
- [default key map](https://github.com/testing-library/user-event/blob/master/src/keyboard/keyMap.ts)
327
- portraying a "default" US-keyboard. You can provide your own local keyboard
328
- mapping per option.
329
-
330
- ```js
331
- userEvent.keyboard('?', {keyboardMap: myOwnLocaleKeyboardMap})
332
- ```
333
-
334
- > Future versions might try to interpolate the modifiers needed to reach a
335
- > printable key on the keyboard. E.g. Automatically pressing `{Shift}` when
336
- > CapsLock is not active and `A` is referenced. If you don't wish this behavior,
337
- > you can pass `autoModify: false` when using `userEvent.keyboard` in your code.
338
-
339
- ### `upload(element, file, [{ clickInit, changeInit }], [options])`
340
-
341
- Uploads file to an `<input>`. For uploading multiple files use `<input>` with
342
- `multiple` attribute and the second `upload` argument must be array then. Also
343
- it's possible to initialize click or change event with using third argument.
344
-
345
- If `options.applyAccept` is set to `true` and there is an `accept` attribute on
346
- the element, files that don't match will be discarded.
347
-
348
- ```jsx
349
- import React from 'react'
350
- import {render, screen} from '@testing-library/react'
351
- import userEvent from '@testing-library/user-event'
352
-
353
- test('upload file', () => {
354
- const file = new File(['hello'], 'hello.png', {type: 'image/png'})
355
-
356
- render(
357
- <div>
358
- <label htmlFor="file-uploader">Upload file:</label>
359
- <input id="file-uploader" type="file" />
360
- </div>,
361
- )
362
- const input = screen.getByLabelText(/upload file/i)
363
- userEvent.upload(input, file)
364
-
365
- expect(input.files[0]).toStrictEqual(file)
366
- expect(input.files.item(0)).toStrictEqual(file)
367
- expect(input.files).toHaveLength(1)
368
- })
369
-
370
- test('upload multiple files', () => {
371
- const files = [
372
- new File(['hello'], 'hello.png', {type: 'image/png'}),
373
- new File(['there'], 'there.png', {type: 'image/png'}),
374
- ]
375
-
376
- render(
377
- <div>
378
- <label htmlFor="file-uploader">Upload file:</label>
379
- <input id="file-uploader" type="file" multiple />
380
- </div>,
381
- )
382
- const input = screen.getByLabelText(/upload file/i)
383
- userEvent.upload(input, files)
384
-
385
- expect(input.files).toHaveLength(2)
386
- expect(input.files[0]).toStrictEqual(files[0])
387
- expect(input.files[1]).toStrictEqual(files[1])
388
- })
389
- ```
390
-
391
- ### `clear(element)`
392
-
393
- Selects the text inside an `<input>` or `<textarea>` and deletes it.
60
+ ## The problem
394
61
 
395
- ```jsx
396
- import React from 'react'
397
- import {render, screen} from '@testing-library/react'
398
- import userEvent from '@testing-library/user-event'
62
+ From
63
+ [testing-library/dom-testing-library#107](https://github.com/testing-library/dom-testing-library/issues/107):
399
64
 
400
- test('clear', () => {
401
- render(<textarea value="Hello, World!" />)
65
+ > [...] it is becoming apparent the need to express user actions on a web page
66
+ > using a higher-level abstraction than [`fireEvent`][fire-event]
402
67
 
403
- userEvent.clear(screen.getByRole('textbox', 'email'))
404
- expect(screen.getByRole('textbox', 'email')).toHaveAttribute('value', '')
405
- })
406
- ```
68
+ ## The solution
407
69
 
408
- ### `selectOptions(element, values)`
409
-
410
- Selects the specified option(s) of a `<select>` or a `<select multiple>`
411
- element.
412
-
413
- ```jsx
414
- import React from 'react'
415
- import {render, screen} from '@testing-library/react'
416
- import userEvent from '@testing-library/user-event'
417
-
418
- test('selectOptions', () => {
419
- render(
420
- <select multiple data-testid="select-multiple">
421
- <option data-testid="val1" value="1">
422
- A
423
- </option>
424
- <option data-testid="val2" value="2">
425
- B
426
- </option>
427
- <option data-testid="val3" value="3">
428
- C
429
- </option>
430
- </select>,
431
- )
432
-
433
- userEvent.selectOptions(screen.getByTestId('select-multiple'), ['1', '3'])
434
-
435
- expect(screen.getByTestId('val1').selected).toBe(true)
436
- expect(screen.getByTestId('val2').selected).toBe(false)
437
- expect(screen.getByTestId('val3').selected).toBe(true)
438
- })
439
- ```
70
+ `user-event` tries to simulate the real events that would happen in the browser
71
+ as the user interacts with it. For example `userEvent.click(checkbox)` would
72
+ change the state of the checkbox.
440
73
 
441
- The `values` parameter can be either an array of values or a singular scalar
442
- value.
74
+ > [The more your tests resemble the way your software is used, the more
75
+ > confidence they can give you.][guiding-principle]
443
76
 
444
- It also accepts option nodes:
77
+ ## Installation
445
78
 
446
- ```js
447
- userEvent.selectOptions(screen.getByTestId('select-multiple'), [
448
- screen.getByText('A'),
449
- screen.getByText('B'),
450
- ])
451
- ```
79
+ With NPM:
452
80
 
453
- ### `deselectOptions(element, values)`
454
-
455
- Remove the selection for the specified option(s) of a `<select multiple>`
456
- element.
457
-
458
- ```jsx
459
- import * as React from 'react'
460
- import {render, screen} from '@testing-library/react'
461
- import userEvent from '@testing-library/user-event'
462
-
463
- test('deselectOptions', () => {
464
- render(
465
- <select multiple>
466
- <option value="1">A</option>
467
- <option value="2">B</option>
468
- <option value="3">C</option>
469
- </select>,
470
- )
471
-
472
- userEvent.selectOptions(screen.getByRole('listbox'), '2')
473
- expect(screen.getByText('B').selected).toBe(true)
474
- userEvent.deselectOptions(screen.getByRole('listbox'), '2')
475
- expect(screen.getByText('B').selected).toBe(false)
476
- // can do multiple at once as well:
477
- // userEvent.deselectOptions(screen.getByRole('listbox'), ['1', '2'])
478
- })
81
+ ```sh
82
+ npm install --save-dev @testing-library/user-event @testing-library/dom
479
83
  ```
480
84
 
481
- The `values` parameter can be either an array of values or a singular scalar
482
- value.
483
-
484
- ### `tab({shift, focusTrap})`
485
-
486
- Fires a tab event changing the document.activeElement in the same way the
487
- browser does.
488
-
489
- Options:
490
-
491
- - `shift` (default `false`) can be true or false to invert tab direction.
492
- - `focusTrap` (default `document`) a container element to restrict the tabbing
493
- within.
494
-
495
- > **A note about tab**:
496
- > [jsdom does not support tabbing](https://github.com/jsdom/jsdom/issues/2102),
497
- > so this feature is a way to enable tests to verify tabbing from the end user's
498
- > perspective. However, this limitation in jsdom will mean that components like
499
- > [focus-trap-react](https://github.com/davidtheclark/focus-trap-react) will not
500
- > work with `userEvent.tab()` or jsdom. For that reason, the `focusTrap` option
501
- > is available to let you ensure your user is restricted within a focus-trap.
502
-
503
- ```jsx
504
- import React from 'react'
505
- import {render, screen} from '@testing-library/react'
506
- import '@testing-library/jest-dom/extend-expect'
507
- import userEvent from '@testing-library/user-event'
508
-
509
- it('should cycle elements in document tab order', () => {
510
- render(
511
- <div>
512
- <input data-testid="element" type="checkbox" />
513
- <input data-testid="element" type="radio" />
514
- <input data-testid="element" type="number" />
515
- </div>,
516
- )
517
-
518
- const [checkbox, radio, number] = screen.getAllByTestId('element')
519
-
520
- expect(document.body).toHaveFocus()
521
-
522
- userEvent.tab()
523
-
524
- expect(checkbox).toHaveFocus()
525
-
526
- userEvent.tab()
527
-
528
- expect(radio).toHaveFocus()
529
-
530
- userEvent.tab()
531
-
532
- expect(number).toHaveFocus()
533
-
534
- userEvent.tab()
535
-
536
- // cycle goes back to the body element
537
- expect(document.body).toHaveFocus()
538
-
539
- userEvent.tab()
540
-
541
- expect(checkbox).toHaveFocus()
542
- })
543
- ```
85
+ With Yarn:
544
86
 
545
- ### `hover(element)`
546
-
547
- Hovers over `element`.
548
-
549
- ```jsx
550
- import React from 'react'
551
- import {render, screen} from '@testing-library/react'
552
- import userEvent from '@testing-library/user-event'
553
- import Tooltip from '../tooltip'
554
-
555
- test('hover', () => {
556
- const messageText = 'Hello'
557
- render(
558
- <Tooltip messageText={messageText}>
559
- <TrashIcon aria-label="Delete" />
560
- </Tooltip>,
561
- )
562
-
563
- userEvent.hover(screen.getByLabelText(/delete/i))
564
- expect(screen.getByText(messageText)).toBeInTheDocument()
565
- userEvent.unhover(screen.getByLabelText(/delete/i))
566
- expect(screen.queryByText(messageText)).not.toBeInTheDocument()
567
- })
87
+ ```sh
88
+ yarn add --dev @testing-library/user-event @testing-library/dom
568
89
  ```
569
90
 
570
- ### `unhover(element)`
91
+ ## Docs
571
92
 
572
- Unhovers out of `element`.
93
+ [**Read The Docs**](https://testing-library.com/docs/ecosystem-user-event) |
94
+ [Edit the docs](https://github.com/testing-library/testing-library-docs)
573
95
 
574
- > See [above](#hoverelement) for an example
96
+ ## Known limitations
575
97
 
576
- ### `paste(element, text, eventInit, options)`
577
-
578
- Allows you to simulate the user pasting some text into an input.
579
-
580
- ```javascript
581
- test('should paste text in input', () => {
582
- render(<MyInput />)
583
-
584
- const text = 'Hello, world!'
585
- userEvent.paste(getByRole('textbox', {name: /paste your greeting/i}), text)
586
- expect(element).toHaveValue(text)
587
- })
588
- ```
589
-
590
- You can use the `eventInit` if what you're pasting should have `clipboardData`
591
- (like `files`).
592
-
593
- ### `specialChars`
594
-
595
- A handful set of special characters used in [type](#typeelement-text-options)
596
- method.
597
-
598
- | Key | Character |
599
- | ---------- | -------------- |
600
- | arrowLeft | `{arrowleft}` |
601
- | arrowRight | `{arrowright}` |
602
- | arrowDown | `{arrowdown}` |
603
- | arrowUp | `{arrowup}` |
604
- | home | `{home}` |
605
- | end | `{end}` |
606
- | enter | `{enter}` |
607
- | escape | `{esc}` |
608
- | delete | `{del}` |
609
- | backspace | `{backspace}` |
610
- | selectAll | `{selectall}` |
611
- | space | `{space}` |
612
- | whitespace | `' '` |
613
-
614
- Usage example:
615
-
616
- ```jsx
617
- import React from 'react'
618
- import {render, screen} from '@testing-library/react'
619
- import userEvent, {specialChars} from '@testing-library/user-event'
620
-
621
- test('delete characters within the selectedRange', () => {
622
- render(
623
- <div>
624
- <label htmlFor="my-input">Example:</label>
625
- <input id="my-input" type="text" value="This is a bad example" />
626
- </div>,
627
- )
628
- const input = screen.getByLabelText(/example/i)
629
- input.setSelectionRange(10, 13)
630
- userEvent.type(input, `${specialChars.backspace}good`)
631
-
632
- expect(input).toHaveValue('This is a good example')
633
- })
634
- ```
98
+ - No `<input type="color" />` support.
99
+ [#423](https://github.com/testing-library/user-event/issues/423#issuecomment-669368863)
635
100
 
636
101
  ## Issues
637
102
 
638
- _Looking to contribute? Look for the [Good First Issue][good-first-issue]
639
- label._
103
+ Looking to contribute? Look for the [Good First Issue][good-first-issue] label.
640
104
 
641
105
  ### 🐛 Bugs
642
106
 
@@ -651,7 +115,15 @@ a 👍. This helps maintainers prioritize what to work on.
651
115
 
652
116
  [**See Feature Requests**][requests]
653
117
 
654
- ## Contributors ✨
118
+ ### ❓ Questions
119
+
120
+ For questions related to using the library, please visit a support community
121
+ instead of filing an issue on GitHub.
122
+
123
+ - [Discord][discord]
124
+ - [Stack Overflow][stackoverflow]
125
+
126
+ ## Contributors
655
127
 
656
128
  Thanks goes to these people ([emoji key][emojis]):
657
129
 
@@ -773,7 +245,12 @@ Thanks goes to these people ([emoji key][emojis]):
773
245
  <td align="center"><a href="https://eugene.coding.blog"><img src="https://avatars.githubusercontent.com/u/13572283?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Eugene Ghanizadeh</b></sub></a><br /><a href="https://github.com/testing-library/user-event/commits?author=loreanvictor" title="Code">💻</a></td>
774
246
  <td align="center"><a href="https://github.com/vicrep"><img src="https://avatars.githubusercontent.com/u/11432241?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Victor Repkow</b></sub></a><br /><a href="https://github.com/testing-library/user-event/commits?author=vicrep" title="Code">💻</a></td>
775
247
  <td align="center"><a href="https://github.com/GreenGremlin"><img src="https://avatars.githubusercontent.com/u/647452?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jonathan Felchlin</b></sub></a><br /><a href="https://github.com/testing-library/user-event/commits?author=GreenGremlin" title="Code">💻</a></td>
776
- <td align="center"><a href="https://github.com/sydneyjodon-wk"><img src="https://avatars.githubusercontent.com/u/51122966?v=4?s=100" width="100px;" alt=""/><br /><sub><b>sydneyjodon-wk</b></sub></a><br /><a href="https://github.com/testing-library/user-event/issues?q=author%3Asydneyjodon-wk" title="Bug reports">🐛</a></td>
248
+ <td align="center"><a href="https://github.com/sydneyjodon-wk"><img src="https://avatars.githubusercontent.com/u/51122966?v=4?s=100" width="100px;" alt=""/><br /><sub><b>sydneyjodon-wk</b></sub></a><br /><a href="https://github.com/testing-library/user-event/issues?q=author%3Asydneyjodon-wk" title="Bug reports">🐛</a> <a href="https://github.com/testing-library/user-event/commits?author=sydneyjodon-wk" title="Code">💻</a></td>
249
+ <td align="center"><a href="https://github.com/codepath2019"><img src="https://avatars.githubusercontent.com/u/49729798?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Charles Magic Woo</b></sub></a><br /><a href="https://github.com/testing-library/user-event/issues?q=author%3Acodepath2019" title="Bug reports">🐛</a></td>
250
+ </tr>
251
+ <tr>
252
+ <td align="center"><a href="https://github.com/mkurcius"><img src="https://avatars.githubusercontent.com/u/1613212?v=4?s=100" width="100px;" alt=""/><br /><sub><b>mkurcius</b></sub></a><br /><a href="https://github.com/testing-library/user-event/commits?author=mkurcius" title="Code">💻</a></td>
253
+ <td align="center"><a href="http://stderr.timfischbach.de"><img src="https://avatars.githubusercontent.com/u/26554?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tim Fischbach</b></sub></a><br /><a href="https://github.com/testing-library/user-event/issues?q=author%3Atf" title="Bug reports">🐛</a></td>
777
254
  </tr>
778
255
  </table>
779
256
 
@@ -787,12 +264,12 @@ Contributions of any kind welcome!
787
264
 
788
265
  ## LICENSE
789
266
 
790
- MIT
267
+ [MIT](LICENSE)
791
268
 
792
269
  <!-- prettier-ignore-start -->
793
270
  [npm]: https://www.npmjs.com
794
271
  [node]: https://nodejs.org
795
- [build-badge]: https://img.shields.io/github/workflow/status/testing-library/user-event/validate/master?logo=github&style=flat-square
272
+ [build-badge]: https://img.shields.io/github/workflow/status/testing-library/user-event/validate/main?logo=github&style=flat-square
796
273
  [build]: https://github.com/testing-library/user-event/actions?query=workflow%3Avalidate
797
274
  [coverage-badge]: https://img.shields.io/codecov/c/github/testing-library/user-event.svg?style=flat-square
798
275
  [coverage]: https://codecov.io/github/testing-library/user-event
@@ -801,15 +278,26 @@ MIT
801
278
  [downloads-badge]: https://img.shields.io/npm/dm/@testing-library/user-event.svg?style=flat-square
802
279
  [npmtrends]: http://www.npmtrends.com/@testing-library/user-event
803
280
  [license-badge]: https://img.shields.io/npm/l/@testing-library/user-event.svg?style=flat-square
804
- [license]: https://github.com/testing-library/user-event/blob/master/LICENSE
281
+ [license]: https://github.com/testing-library/user-event/blob/main/LICENSE
805
282
  [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
806
283
  [prs]: http://makeapullrequest.com
807
284
  [coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
808
- [coc]: https://github.com/testing-library/user-event/blob/master/other/CODE_OF_CONDUCT.md
285
+ [coc]: https://github.com/testing-library/user-event/blob/main/other/CODE_OF_CONDUCT.md
286
+ [github-watch-badge]: https://img.shields.io/github/watchers/testing-library/user-event.svg?style=social
287
+ [github-watch]: https://github.com/testing-library/user-event/watchers
288
+ [github-star-badge]: https://img.shields.io/github/stars/testing-library/user-event.svg?style=social
289
+ [github-star]: https://github.com/testing-library/user-event/stargazers
290
+ [twitter]: https://twitter.com/intent/tweet?text=Check%20out%20user-event%20by%20%40@TestingLib%20https%3A%2F%2Fgithub.com%2Ftesting-library%2Fuser-event%20%F0%9F%91%8D
291
+ [twitter-badge]: https://img.shields.io/twitter/url/https/github.com/testing-library/user-event.svg?style=social
809
292
  [emojis]: https://github.com/all-contributors/all-contributors#emoji-key
810
293
  [all-contributors]: https://github.com/all-contributors/all-contributors
811
294
  [all-contributors-badge]: https://img.shields.io/github/all-contributors/testing-library/user-event?color=orange&style=flat-square
295
+ [guiding-principle]: https://twitter.com/kentcdodds/status/977018512689455106
812
296
  [bugs]: https://github.com/testing-library/user-event/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Acreated-desc+label%3Abug
813
297
  [requests]: https://github.com/testing-library/user-event/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement
814
298
  [good-first-issue]: https://github.com/testing-library/user-event/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement+label%3A%22good+first+issue%22
299
+ [fire-event]: https://testing-library.com/docs/dom-testing-library/api-events#fireevent
300
+ [discord-badge]: https://img.shields.io/discord/723559267868737556.svg?color=7389D8&labelColor=6A7EC2&logo=discord&logoColor=ffffff&style=flat-square
301
+ [discord]: https://discord.gg/testing-library
302
+ [stackoverflow]: https://stackoverflow.com/questions/tagged/user-event
815
303
  <!-- prettier-ignore-end -->
@@ -0,0 +1,3 @@
1
+ declare module '@testing-library/dom/dist/helpers' {
2
+ export function getWindowFromNode(node: Node): Window
3
+ }
@@ -18,8 +18,7 @@ function getKeyEventProps(keyDef, state) {
18
18
  shiftKey: state.modifiers.shift,
19
19
 
20
20
  /** @deprecated use code instead */
21
- keyCode: (_keyDef$keyCode = keyDef.keyCode) != null ? _keyDef$keyCode : // istanbul ignore next
22
- ((_keyDef$key = keyDef.key) == null ? void 0 : _keyDef$key.length) === 1 ? keyDef.key.charCodeAt(0) : undefined
21
+ keyCode: (_keyDef$keyCode = keyDef.keyCode) != null ? _keyDef$keyCode : ((_keyDef$key = keyDef.key) == null ? void 0 : _keyDef$key.length) === 1 ? keyDef.key.charCodeAt(0) : undefined
23
22
  };
24
23
  }
25
24
 
@@ -108,6 +108,6 @@ function isPrintableCharacter(startBracket, descriptor) {
108
108
 
109
109
  function getErrorMessage(expected, found, text) {
110
110
  return `Expected ${expected} but found "${found != null ? found : ''}" in "${text}"
111
- See https://github.com/testing-library/user-event/blob/master/README.md#keyboardtext-options
111
+ See https://github.com/testing-library/user-event/blob/main/README.md#keyboardtext-options
112
112
  for more information about how userEvent parses your input.`;
113
113
  }
@@ -1,7 +1,5 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
4
-
5
3
  Object.defineProperty(exports, "__esModule", {
6
4
  value: true
7
5
  });
@@ -18,6 +16,10 @@ var plugins = _interopRequireWildcard(require("./plugins"));
18
16
 
19
17
  var _getEventProps = require("./getEventProps");
20
18
 
19
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
20
+
21
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
22
+
21
23
  async function keyboardImplementation(text, options, state) {
22
24
  const {
23
25
  document
@@ -12,8 +12,8 @@ var _utils = require("../../utils");
12
12
  * https://w3c.github.io/uievents-code/#key-arrowpad-section
13
13
  */
14
14
  const keydownBehavior = [{
15
- // TODO: implement for textarea and contentEditable
16
- matches: (keyDef, element) => (keyDef.key === 'ArrowLeft' || keyDef.key === 'ArrowRight') && (0, _utils.isElementType)(element, 'input'),
15
+ // TODO: implement for contentEditable
16
+ matches: (keyDef, element) => (keyDef.key === 'ArrowLeft' || keyDef.key === 'ArrowRight') && (0, _utils.isElementType)(element, ['input', 'textarea']),
17
17
  handle: (keyDef, element) => {
18
18
  var _ref;
19
19
 
@@ -71,8 +71,7 @@ const keydownBehavior = [{
71
71
  }];
72
72
  exports.keydownBehavior = keydownBehavior;
73
73
  const keypressBehavior = [{
74
- matches: (keyDef, element) => keyDef.key === 'Enter' && ((0, _utils.isClickableInput)(element) || // Links with href defined should handle Enter the same as a click
75
- (0, _utils.isElementType)(element, 'a') && Boolean(element.href)),
74
+ matches: (keyDef, element) => keyDef.key === 'Enter' && ((0, _utils.isClickableInput)(element) || (0, _utils.isElementType)(element, 'a') && Boolean(element.href)),
76
75
  handle: (keyDef, element, options, state) => {
77
76
  _dom.fireEvent.click(element, (0, _getEventProps.getMouseEventProps)(state));
78
77
  }
@@ -1,7 +1,5 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
4
-
5
3
  Object.defineProperty(exports, "__esModule", {
6
4
  value: true
7
5
  });
@@ -17,6 +15,10 @@ var characterKeys = _interopRequireWildcard(require("./character"));
17
15
 
18
16
  var functionalKeys = _interopRequireWildcard(require("./functional"));
19
17
 
18
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
19
+
20
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
21
+
20
22
  const replaceBehavior = [{
21
23
  matches: (keyDef, element) => keyDef.key === 'selectall' && (0, _utils.isElementType)(element, ['input', 'textarea']),
22
24
  handle: (keyDef, element, options, state) => {
@@ -6,3 +6,12 @@ export declare function fireInputEvent(element: HTMLElement, { newValue, newSele
6
6
  [k: string]: unknown;
7
7
  };
8
8
  }): void;
9
+ declare const initial: unique symbol;
10
+ declare const onBlur: unique symbol;
11
+ declare global {
12
+ interface Element {
13
+ [initial]?: string;
14
+ [onBlur]?: EventListener;
15
+ }
16
+ }
17
+ export {};
@@ -17,9 +17,9 @@ function fireInputEvent(element, {
17
17
  // apply the changes before firing the input event, so that input handlers can access the altered dom and selection
18
18
  if ((0, _utils.isContentEditable)(element)) {
19
19
  applyNative(element, 'textContent', newValue);
20
- }
21
- /* istanbul ignore else */
22
- else if ((0, _utils.isElementType)(element, ['input', 'textarea'])) {
20
+ } else
21
+ /* istanbul ignore else */
22
+ if ((0, _utils.isElementType)(element, ['input', 'textarea'])) {
23
23
  applyNative(element, 'value', newValue);
24
24
  } else {
25
25
  // TODO: properly type guard
@@ -31,32 +31,35 @@ function fireInputEvent(element, {
31
31
  _dom.fireEvent.input(element, { ...eventOverrides
32
32
  });
33
33
 
34
- setSelectionRangeAfterInputHandler(element, newValue);
34
+ setSelectionRangeAfterInputHandler(element, newValue, newSelectionStart);
35
35
  }
36
36
 
37
37
  function setSelectionRangeAfterInput(element, newSelectionStart) {
38
38
  (0, _utils.setSelectionRange)(element, newSelectionStart, newSelectionStart);
39
39
  }
40
40
 
41
- function setSelectionRangeAfterInputHandler(element, newValue) {
42
- // if we *can* change the selection start, then we will if the new value
43
- // is the same as the current value (so it wasn't programatically changed
44
- // when the fireEvent.input was triggered).
45
- // The reason we have to do this at all is because it actually *is*
46
- // programmatically changed by fireEvent.input, so we have to simulate the
47
- // browser's default behavior
41
+ function setSelectionRangeAfterInputHandler(element, newValue, newSelectionStart) {
48
42
  const value = (0, _utils.getValue)(element); // don't apply this workaround on elements that don't necessarily report the visible value - e.g. number
49
43
  // TODO: this could probably be only applied when there is keyboardState.carryValue
50
44
 
51
- const expectedValue = value === newValue || value === '' && (0, _utils.hasUnreliableEmptyValue)(element);
45
+ const isUnreliableValue = value === '' && (0, _utils.hasUnreliableEmptyValue)(element);
46
+
47
+ if (!isUnreliableValue && value === newValue) {
48
+ const {
49
+ selectionStart
50
+ } = (0, _utils.getSelectionRange)(element);
52
51
 
53
- if (!expectedValue) {
54
- // If the currentValue is different than the expected newValue and we *can*
55
- // change the selection range, than we should set it to the length of the
56
- // currentValue to ensure that the browser behavior is mimicked.
57
- (0, _utils.setSelectionRange)(element, value.length, value.length);
52
+ if (selectionStart === value.length) {
53
+ // The value was changed as expected, but the cursor was moved to the end
54
+ // TODO: this could probably be only applied when we work around a framework setter on the element in applyNative
55
+ (0, _utils.setSelectionRange)(element, newSelectionStart, newSelectionStart);
56
+ }
58
57
  }
59
58
  }
59
+
60
+ const initial = Symbol('initial input value/textContent');
61
+ const onBlur = Symbol('onBlur');
62
+
60
63
  /**
61
64
  * React tracks the changes on element properties.
62
65
  * This workaround tries to alter the DOM element without React noticing,
@@ -64,17 +67,42 @@ function setSelectionRangeAfterInputHandler(element, newValue) {
64
67
  *
65
68
  * @see https://github.com/facebook/react/blob/148f8e497c7d37a3c7ab99f01dec2692427272b1/packages/react-dom/src/client/inputValueTracking.js#L51-L104
66
69
  */
67
-
68
-
69
70
  function applyNative(element, propName, propValue) {
70
71
  const descriptor = Object.getOwnPropertyDescriptor(element, propName);
71
72
  const nativeDescriptor = Object.getOwnPropertyDescriptor(element.constructor.prototype, propName);
72
73
 
73
74
  if (descriptor && nativeDescriptor) {
74
75
  Object.defineProperty(element, propName, nativeDescriptor);
76
+ } // Keep track of the initial value to determine if a change event should be dispatched.
77
+ // CONSTRAINT: We can not determine what happened between focus event and our first API call.
78
+
79
+
80
+ if (element[initial] === undefined) {
81
+ element[initial] = String(element[propName]);
75
82
  }
76
83
 
77
- element[propName] = propValue;
84
+ element[propName] = propValue; // Add an event listener for the blur event to the capture phase on the window.
85
+ // CONSTRAINT: Currently there is no cross-platform solution to unshift the event handler stack.
86
+ // Our change event might occur after other event handlers on the blur event have been processed.
87
+
88
+ if (!element[onBlur]) {
89
+ var _element$ownerDocumen;
90
+
91
+ (_element$ownerDocumen = element.ownerDocument.defaultView) == null ? void 0 : _element$ownerDocumen.addEventListener('blur', element[onBlur] = () => {
92
+ const initV = element[initial]; // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
93
+
94
+ delete element[onBlur]; // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
95
+
96
+ delete element[initial];
97
+
98
+ if (String(element[propName]) !== initV) {
99
+ _dom.fireEvent.change(element);
100
+ }
101
+ }, {
102
+ capture: true,
103
+ once: true
104
+ });
105
+ }
78
106
 
79
107
  if (descriptor) {
80
108
  Object.defineProperty(element, propName, descriptor);
@@ -80,6 +80,11 @@ function setSelectionRange(element, newSelectionStart, newSelectionEnd) {
80
80
  selectionStart: newSelectionStart,
81
81
  selectionEnd: newSelectionEnd
82
82
  };
83
+ } // Moving the selection inside <input> or <textarea> does not alter the document Selection.
84
+
85
+
86
+ if ((0, _isElementType.isElementType)(element, 'input') || (0, _isElementType.isElementType)(element, 'textarea')) {
87
+ return;
83
88
  }
84
89
 
85
90
  const range = element.ownerDocument.createRange();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@testing-library/user-event",
3
- "version": "13.1.7",
3
+ "version": "13.2.1",
4
4
  "description": "Fire events the same way the user does",
5
5
  "main": "dist/index.js",
6
6
  "keywords": [
@@ -49,7 +49,7 @@
49
49
  "is-ci": "^2.0.0",
50
50
  "jest-in-case": "^1.0.2",
51
51
  "jest-serializer-ansi": "^1.0.3",
52
- "kcd-scripts": "^7.5.1",
52
+ "kcd-scripts": "^11.1.0",
53
53
  "react": "^17.0.2",
54
54
  "react-dom": "^17.0.2",
55
55
  "typescript": "^4.1.2"
@@ -1 +0,0 @@
1
- "use strict";