From 20f6c765c37b22cbbb900cd488b7e55af88793e9 Mon Sep 17 00:00:00 2001 From: Philipp Fritsche Date: Fri, 29 Oct 2021 18:07:59 +0000 Subject: [PATCH] fix: set `KeyboardEvent.charCode` on `keypress` --- src/keyboard/keyboardImplementation.ts | 8 ++++---- tests/react/keyboard.tsx | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/keyboard/keyboardImplementation.ts b/src/keyboard/keyboardImplementation.ts index 1f68f930..379ce86e 100644 --- a/src/keyboard/keyboardImplementation.ts +++ b/src/keyboard/keyboardImplementation.ts @@ -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( diff --git a/tests/react/keyboard.tsx b/tests/react/keyboard.tsx index 1249d83a..20299c5d 100644 --- a/tests/react/keyboard.tsx +++ b/tests/react/keyboard.tsx @@ -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() + render() + 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) +})