-
Notifications
You must be signed in to change notification settings - Fork 240
/
keyboard.tsx
37 lines (30 loc) 路 1.43 KB
/
keyboard.tsx
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
import React, {useState} from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '#src'
// Run twice to verify we handle this correctly no matter
// if React applies its magic before or after our document preparation.
test.each([0, 1])('maintain cursor position on controlled input', async () => {
function Input({initialValue}: {initialValue: string}) {
const [val, setVal] = useState(initialValue)
return <input value={val} onChange={e => setVal(e.target.value)} />
}
render(<Input initialValue="acd" />)
screen.getByRole('textbox').focus()
screen.getByRole<HTMLInputElement>('textbox').setSelectionRange(1, 1)
await userEvent.keyboard('b')
expect(screen.getByRole('textbox')).toHaveValue('abcd')
expect(screen.getByRole('textbox')).toHaveProperty('selectionStart', 2)
expect(screen.getByRole('textbox')).toHaveProperty('selectionEnd', 2)
})
test('trigger Synthetic `keypress` event for printable characters', async () => {
const onKeyPress = jest.fn<unknown, [React.KeyboardEvent]>()
render(<input onKeyPress={onKeyPress} />)
const user = userEvent.setup()
screen.getByRole('textbox').focus()
await user.keyboard('a')
expect(onKeyPress).toHaveBeenCalledTimes(1)
expect(onKeyPress.mock.calls[0][0]).toHaveProperty('charCode', 97)
await user.keyboard('[Enter]')
expect(onKeyPress).toHaveBeenCalledTimes(2)
expect(onKeyPress.mock.calls[1][0]).toHaveProperty('charCode', 13)
})