Skip to content

onKeyDown charCode/keyCode/which is 0 #842

Closed
@make-github-pseudonymous-again

Description

  • @testing-library/user-event version: a5ca2e4
  • Testing Framework and version: NA
  • DOM Environment: NA

Problem description

Adding the following test to src/keyboard/keyboardAction.ts

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

  await userEvent.keyboard('a')
  expect(onKeyDown).toHaveBeenCalledTimes(1)
  expect(onKeyDown.mock.calls[0][0]).toHaveProperty('charCode', 65)

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

yields the error

    trigger Synthetic `keydown` event for printable characters

    expect(received).toHaveProperty(path, value)

    Expected path: "charCode"

    Expected value: 65
    Received value: 0

      43 |   await userEvent.keyboard('a')
      44 |   expect(onKeyDown).toHaveBeenCalledTimes(1)
    > 45 |   expect(onKeyDown.mock.calls[0][0]).toHaveProperty('charCode', 65)
         |                                      ^
      46 |
      47 |   await userEvent.keyboard('[Enter]')
      48 |   expect(onKeyDown).toHaveBeenCalledTimes(2)

      at Object.<anonymous> (tests/react/keyboard.tsx:45:38)

Testing only [Enter] yields the same error. Found this while having trouble with my tests because UI relies on the charCode of keydown events. Expected?

The MDN docs on keyDown hint at the fact that codes should be present, but I do not know the specs. Missing implementation? I can help with providing a fix.

Suggested solution

Some patch was made to keypress to fix a similar issue (see 55e194a).
Similar patch should probably be made to keyup and keydown too, although the key mapping is not the same.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions