Skip to content

Commit

Permalink
fix(keyboard): set KeyboardEvent.charCode on keypress (#771)
Browse files Browse the repository at this point in the history
  • Loading branch information
ph-fritsche authored Oct 30, 2021
1 parent 5434f3f commit 4f04a3d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/keyboard/keyboardImplementation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,10 @@ function keypress(
) {
const element = getCurrentElement()

const unpreventedDefault = fireEvent.keyPress(
element,
getKeyEventProps(keyDef, state),
)
const unpreventedDefault = fireEvent.keyPress(element, {
...getKeyEventProps(keyDef, state),
charCode: keyDef.key === 'Enter' ? 13 : String(keyDef.key).charCodeAt(0),
})

if (unpreventedDefault) {
applyPlugins(
Expand Down
14 changes: 14 additions & 0 deletions tests/react/keyboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,17 @@ test.each([0, 1])('maintain cursor position on controlled input', () => {
expect(screen.getByRole('textbox')).toHaveProperty('selectionStart', 2)
expect(screen.getByRole('textbox')).toHaveProperty('selectionEnd', 2)
})

test('trigger Synthetic `keypress` event for printable characters', () => {
const onKeyPress = jest.fn<unknown, [React.KeyboardEvent]>()
render(<input onKeyPress={onKeyPress} />)
screen.getByRole('textbox').focus()

userEvent.keyboard('a')
expect(onKeyPress).toHaveBeenCalledTimes(1)
expect(onKeyPress.mock.calls[0][0]).toHaveProperty('charCode', 97)

userEvent.keyboard('[Enter]')
expect(onKeyPress).toHaveBeenCalledTimes(2)
expect(onKeyPress.mock.calls[1][0]).toHaveProperty('charCode', 13)
})

0 comments on commit 4f04a3d

Please sign in to comment.