/
type.js
573 lines (507 loc) Β· 16.6 KB
/
type.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
import React, {Fragment} from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '..'
import {setup, addListeners} from './helpers/utils'
import './helpers/customElement'
it('types text in input', async () => {
const {element, getEventCalls} = setup(<input />)
await userEvent.type(element, 'Sup')
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: S (83)
keypress: S (83)
input: "{CURSOR}" -> "S"
keyup: S (83)
keydown: u (117)
keypress: u (117)
input: "S{CURSOR}" -> "Su"
keyup: u (117)
keydown: p (112)
keypress: p (112)
input: "Su{CURSOR}" -> "Sup"
keyup: p (112)
`)
})
it('types text inside custom element', async () => {
const {
container: {firstChild: customElement},
} = render(<custom-el />)
const inputEl = customElement.shadowRoot.querySelector('input')
const {getEventCalls} = addListeners(inputEl)
await userEvent.type(inputEl, 'Sup')
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: S (83)
keypress: S (83)
input: "{CURSOR}" -> "S"
keyup: S (83)
keydown: u (117)
keypress: u (117)
input: "S{CURSOR}" -> "Su"
keyup: u (117)
keydown: p (112)
keypress: p (112)
input: "Su{CURSOR}" -> "Sup"
keyup: p (112)
`)
})
it('types text in textarea', async () => {
const {element, getEventCalls} = setup(<textarea />)
await userEvent.type(element, 'Sup')
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: S (83)
keypress: S (83)
input: "{CURSOR}" -> "S"
keyup: S (83)
keydown: u (117)
keypress: u (117)
input: "S{CURSOR}" -> "Su"
keyup: u (117)
keydown: p (112)
keypress: p (112)
input: "Su{CURSOR}" -> "Sup"
keyup: p (112)
`)
})
test('should append text all at once', async () => {
const {element, getEventCalls} = setup(<input />)
await userEvent.type(element, 'Sup', {allAtOnce: true})
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
input: "{CURSOR}" -> "Sup"
`)
})
test('does not fire input event when keypress calls prevent default', async () => {
const {element, getEventCalls} = setup(
<input onKeyPress={e => e.preventDefault()} />,
)
await userEvent.type(element, 'a')
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: a (97)
keypress: a (97)
keyup: a (97)
`)
})
test('does not fire keypress or input events when keydown calls prevent default', async () => {
const {element, getEventCalls} = setup(
<input onKeyDown={e => e.preventDefault()} />,
)
await userEvent.type(element, 'a')
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: a (97)
keyup: a (97)
`)
})
// TODO: Let's migrate these tests to use the setup util
test('should not type when event.preventDefault() is called', async () => {
const onChange = jest.fn()
const onKeydown = jest
.fn()
.mockImplementation(event => event.preventDefault())
render(
<input data-testid="input" onKeyDown={onKeydown} onChange={onChange} />,
)
const text = 'Hello, world!'
await userEvent.type(screen.getByTestId('input'), text)
expect(onKeydown).toHaveBeenCalledTimes(text.length)
expect(onChange).toHaveBeenCalledTimes(0)
expect(screen.getByTestId('input')).not.toHaveProperty('value', text)
})
test.each(['input', 'textarea'])(
'should not type when <%s> is disabled',
async type => {
const onChange = jest.fn()
render(
React.createElement(type, {
'data-testid': 'input',
onChange,
disabled: true,
}),
)
const text = 'Hello, world!'
await userEvent.type(screen.getByTestId('input'), text)
expect(onChange).not.toHaveBeenCalled()
expect(screen.getByTestId('input')).toHaveProperty('value', '')
},
)
test.each(['input', 'textarea'])(
'should not type when <%s> is readOnly',
async type => {
const onChange = jest.fn()
const onKeyDown = jest.fn()
const onKeyPress = jest.fn()
const onKeyUp = jest.fn()
render(
React.createElement(type, {
'data-testid': 'input',
onChange,
onKeyDown,
onKeyPress,
onKeyUp,
readOnly: true,
}),
)
const text = 'Hello, world!'
await userEvent.type(screen.getByTestId('input'), text)
expect(onKeyDown).toHaveBeenCalledTimes(text.length)
expect(onKeyPress).toHaveBeenCalledTimes(text.length)
expect(onKeyUp).toHaveBeenCalledTimes(text.length)
expect(onChange).not.toHaveBeenCalled()
expect(screen.getByTestId('input')).toHaveProperty('value', '')
},
)
test('does not type when readOnly even with allAtOnce', () => {
const handleChange = jest.fn()
render(<input data-testid="input" readOnly onChange={handleChange} />)
userEvent.type(screen.getByTestId('input'), 'hi', {allAtOnce: true})
expect(handleChange).not.toHaveBeenCalled()
})
test('does not type when disabled even with allAtOnce', () => {
const handleChange = jest.fn()
render(<input data-testid="input" disabled onChange={handleChange} />)
userEvent.type(screen.getByTestId('input'), 'hi', {allAtOnce: true})
expect(handleChange).not.toHaveBeenCalled()
})
test('should delay the typing when opts.delay is not 0', async () => {
const inputValues = [{timestamp: Date.now(), value: ''}]
const onInput = jest.fn(event => {
inputValues.push({timestamp: Date.now(), value: event.target.value})
})
render(<input data-testid="input" onInput={onInput} />)
const text = 'Hello, world!'
const delay = 10
await userEvent.type(screen.getByTestId('input'), text, {
delay,
})
expect(onInput).toHaveBeenCalledTimes(text.length)
for (let index = 1; index < inputValues.length; index++) {
const {timestamp, value} = inputValues[index]
expect(timestamp - inputValues[index - 1].timestamp).toBeGreaterThanOrEqual(
delay,
)
expect(value).toBe(text.slice(0, index))
}
})
test.each(['input', 'textarea'])(
'should type text in <%s> all at once',
type => {
const onChange = jest.fn()
render(
React.createElement(type, {
'data-testid': 'input',
onChange,
}),
)
const text = 'Hello, world!'
userEvent.type(screen.getByTestId('input'), text, {
allAtOnce: true,
})
expect(onChange).toHaveBeenCalledTimes(1)
expect(screen.getByTestId('input')).toHaveProperty('value', text)
},
)
test.each(['input', 'textarea'])(
'should enter text in <%s> up to maxLength if provided',
async type => {
const onChange = jest.fn()
const onKeyDown = jest.fn()
const onKeyPress = jest.fn()
const onKeyUp = jest.fn()
const maxLength = 10
render(
React.createElement(type, {
'data-testid': 'input',
onChange,
onKeyDown,
onKeyPress,
onKeyUp,
maxLength,
}),
)
const text = 'superlongtext'
const slicedText = text.slice(0, maxLength)
const inputEl = screen.getByTestId('input')
await userEvent.type(inputEl, text)
expect(inputEl).toHaveProperty('value', slicedText)
expect(onChange).toHaveBeenCalledTimes(slicedText.length)
expect(onKeyPress).toHaveBeenCalledTimes(text.length)
expect(onKeyDown).toHaveBeenCalledTimes(text.length)
expect(onKeyUp).toHaveBeenCalledTimes(text.length)
inputEl.value = ''
onChange.mockClear()
onKeyPress.mockClear()
onKeyDown.mockClear()
onKeyUp.mockClear()
userEvent.type(inputEl, text, {
allAtOnce: true,
})
expect(inputEl).toHaveProperty('value', slicedText)
expect(onChange).toHaveBeenCalledTimes(1)
expect(onKeyPress).not.toHaveBeenCalled()
expect(onKeyDown).not.toHaveBeenCalled()
expect(onKeyUp).not.toHaveBeenCalled()
},
)
test.each(['input', 'textarea'])(
'should append text in <%s> up to maxLength if provided',
async type => {
const onChange = jest.fn()
const onKeyDown = jest.fn()
const onKeyPress = jest.fn()
const onKeyUp = jest.fn()
const maxLength = 10
render(
React.createElement(type, {
'data-testid': 'input',
onChange,
onKeyDown,
onKeyPress,
onKeyUp,
maxLength,
}),
)
const text1 = 'superlong'
const text2 = 'text'
const text = text1 + text2
const slicedText = text.slice(0, maxLength)
const inputEl = screen.getByTestId('input')
await userEvent.type(inputEl, text1)
await userEvent.type(inputEl, text2)
expect(inputEl).toHaveProperty('value', slicedText)
expect(onChange).toHaveBeenCalledTimes(slicedText.length)
expect(onKeyPress).toHaveBeenCalledTimes(text.length)
expect(onKeyDown).toHaveBeenCalledTimes(text.length)
expect(onKeyUp).toHaveBeenCalledTimes(text.length)
inputEl.value = ''
onChange.mockClear()
onKeyPress.mockClear()
onKeyDown.mockClear()
onKeyUp.mockClear()
userEvent.type(inputEl, text, {
allAtOnce: true,
})
expect(inputEl).toHaveProperty('value', slicedText)
expect(onChange).toHaveBeenCalledTimes(1)
expect(onKeyPress).not.toHaveBeenCalled()
expect(onKeyDown).not.toHaveBeenCalled()
expect(onKeyUp).not.toHaveBeenCalled()
},
)
test('should fire events on the currently focused element', async () => {
const changeFocusLimit = 7
const onKeyDown = jest.fn(event => {
if (event.target.value.length === changeFocusLimit) {
screen.getByTestId('input2').focus()
}
})
render(
<Fragment>
<input data-testid="input1" onKeyDown={onKeyDown} />
<input data-testid="input2" />
</Fragment>,
)
const text = 'Hello, world!'
const input1 = screen.getByTestId('input1')
const input2 = screen.getByTestId('input2')
await userEvent.type(input1, text)
expect(input1).toHaveValue(text.slice(0, changeFocusLimit))
expect(input2).toHaveValue(text.slice(changeFocusLimit))
expect(input2).toHaveFocus()
})
test('should enter text up to maxLength of the current element if provided', async () => {
const changeFocusLimit = 7
const input2MaxLength = 2
const onKeyDown = jest.fn(event => {
if (event.target.value.length === changeFocusLimit) {
screen.getByTestId('input2').focus()
}
})
render(
<>
<input data-testid="input" onKeyDown={onKeyDown} />
<input data-testid="input2" maxLength={input2MaxLength} />
</>,
)
const text = 'Hello, world!'
const input2ExpectedValue = text.slice(
changeFocusLimit,
changeFocusLimit + input2MaxLength,
)
const input1 = screen.getByTestId('input')
const input2 = screen.getByTestId('input2')
await userEvent.type(input1, text)
expect(input1).toHaveValue(text.slice(0, changeFocusLimit))
expect(input2).toHaveValue(input2ExpectedValue)
expect(input2).toHaveFocus()
})
test('should replace selected text one by one', async () => {
const onChange = jest.fn()
const {
container: {firstChild: input},
} = render(<input defaultValue="hello world" onChange={onChange} />)
const selectionStart = 'hello world'.search('world')
const selectionEnd = selectionStart + 'world'.length
input.setSelectionRange(selectionStart, selectionEnd)
await userEvent.type(input, 'friend')
expect(onChange).toHaveBeenCalledTimes('friend'.length)
expect(input).toHaveValue('hello friend')
})
test('should replace selected text one by one up to maxLength if provided', async () => {
const maxLength = 10
const onChange = jest.fn()
const {
container: {firstChild: input},
} = render(
<input
defaultValue="hello world"
onChange={onChange}
maxLength={maxLength}
/>,
)
const selectionStart = 'hello world'.search('world')
const selectionEnd = selectionStart + 'world'.length
input.setSelectionRange(selectionStart, selectionEnd)
const resultIfUnlimited = 'hello friend'
const slicedText = resultIfUnlimited.slice(0, maxLength)
await userEvent.type(input, 'friend')
const truncatedCharCount = resultIfUnlimited.length - slicedText.length
expect(onChange).toHaveBeenCalledTimes('friend'.length - truncatedCharCount)
expect(input).toHaveValue(slicedText)
})
test('should replace selected text all at once', async () => {
const onChange = jest.fn()
const {
container: {firstChild: input},
} = render(<input defaultValue="hello world" onChange={onChange} />)
const selectionStart = 'hello world'.search('world')
const selectionEnd = selectionStart + 'world'.length
input.setSelectionRange(selectionStart, selectionEnd)
await userEvent.type(input, 'friend', {allAtOnce: true})
expect(onChange).toHaveBeenCalledTimes(1)
expect(input).toHaveValue('hello friend')
})
test('does not continue firing events when disabled during typing', async () => {
function TestComp() {
const [disabled, setDisabled] = React.useState(false)
return <input disabled={disabled} onChange={() => setDisabled(true)} />
}
const {
container: {firstChild: input},
} = render(<TestComp />)
await userEvent.type(input, 'hi there')
expect(input).toHaveValue('h')
})
function DollarInput({initialValue = ''}) {
const [value, setValue] = React.useState(initialValue)
function handleChange(event) {
const val = event.target.value
const withoutDollar = val.replace(/\$/g, '')
const num = Number(withoutDollar)
if (Number.isNaN(num)) return
setValue(`$${withoutDollar}`)
}
return <input value={value} type="text" onChange={handleChange} />
}
test('typing into a controlled input works', async () => {
const {element, getEventCalls} = setup(<DollarInput />)
await userEvent.type(element, '23')
expect(element.value).toBe('$23')
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: 2 (50)
keypress: 2 (50)
input: "{CURSOR}" -> "2"
keyup: 2 (50)
keydown: 3 (51)
keypress: 3 (51)
input: "$2{CURSOR}" -> "$23"
keyup: 3 (51)
`)
})
test('typing in the middle of a controlled input works', async () => {
const {element, getEventCalls} = setup(<DollarInput initialValue="$23" />)
element.setSelectionRange(2, 2)
await userEvent.type(element, '1')
expect(element.value).toBe('$213')
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: 1 (49)
keypress: 1 (49)
input: "$2{CURSOR}3" -> "$213"
keyup: 1 (49)
`)
})
test('ignored {backspace} in controlled input', async () => {
const {element, getEventCalls} = setup(<DollarInput initialValue="$23" />)
element.setSelectionRange(1, 1)
await userEvent.type(element, '{backspace}')
// this is the same behavior in the browser.
// in our case, when you try to backspace the "$", our event handler
// will ignore that change and React resets the value to what it was
// before. When the value is set programmatically to something different
// from what was expected based on the input event, the browser sets
// the selection start and end to the end of the input
expect(element.selectionStart).toBe(element.value.length)
expect(element.selectionEnd).toBe(element.value.length)
await userEvent.type(element, '4')
expect(element.value).toBe('$234')
// the backslash in the inline snapshot is to escape the $ before {CURSOR}
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: Backspace (8)
input: "\${CURSOR}23" -> "23"
keyup: Backspace (8)
keydown: 4 (52)
keypress: 4 (52)
input: "$23{CURSOR}" -> "$234"
keyup: 4 (52)
`)
})
// https://github.com/testing-library/user-event/issues/321
test('typing in a textarea with existing text', async () => {
const {element, getEventCalls} = setup(<textarea defaultValue="Hello, " />)
await userEvent.type(element, '12')
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: 1 (49)
keypress: 1 (49)
input: "Hello, {CURSOR}" -> "Hello, 1"
keyup: 1 (49)
keydown: 2 (50)
keypress: 2 (50)
input: "Hello, 1{CURSOR}" -> "Hello, 12"
keyup: 2 (50)
`)
expect(element).toHaveValue('Hello, 12')
})
// https://github.com/testing-library/user-event/issues/321
test('accepts an initialSelectionStart and initialSelectionEnd', async () => {
const {element, getEventCalls} = setup(<textarea defaultValue="Hello, " />)
element.setSelectionRange(0, 0)
await userEvent.type(element, '12', {
initialSelectionStart: element.selectionStart,
initialSelectionEnd: element.selectionEnd,
})
expect(getEventCalls()).toMatchInlineSnapshot(`
focus
keydown: 1 (49)
keypress: 1 (49)
input: "{CURSOR}Hello, " -> "1Hello, "
keyup: 1 (49)
keydown: 2 (50)
keypress: 2 (50)
input: "1{CURSOR}Hello, " -> "12Hello, "
keyup: 2 (50)
`)
expect(element).toHaveValue('12Hello, ')
})
// https://github.com/testing-library/user-event/issues/316#issuecomment-640199908
test('can type into an input with type `email`', async () => {
const {element} = setup(<input type="email" />)
const email = 'yo@example.com'
await userEvent.type(element, email)
expect(element).toHaveValue(email)
})