Skip to content

Commit

Permalink
fix: set KeyboardEvent.charCode on keypress
Browse files Browse the repository at this point in the history
  • Loading branch information
ph-fritsche committed Oct 29, 2021
1 parent e39177e commit 20f6c76
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 20f6c76

Please sign in to comment.