Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support KeyboardEvent.key in Modal #75

Closed
ericgio opened this issue Mar 2, 2023 · 0 comments · Fixed by #76
Closed

Support KeyboardEvent.key in Modal #75

ericgio opened this issue Mar 2, 2023 · 0 comments · Fixed by #76

Comments

@ericgio
Copy link

ericgio commented Mar 2, 2023

Is your feature request related to a problem? Please describe

I ran into an issue testing React-Bootstrap's Offcanvas component, which uses Modal under the hood. My test fails when asserting that the component is closed after pressing the Esc key:

it('closes the drawer when the esc key is pressed', async () => {
  render(<Offcanvas />);

  expect(screen.queryByRole('dialog')).toBeInTheDocument();
  await userEvent.keyboard('{Escape}');
  expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});

Modal uses KeyBoardEvent.keyCode to check whether the Esc key has been pressed. However, KeyboardEvent.keyCode is deprecated and no longer supported in @testing-library/user-event.

Describe the solution you'd like

Given that KeyboardEvent.keyCode is deprecated, it seems like a good idea to add support for KeyboardEvent.key eg:

const escPressed = e.keyCode === 27 || e.key === 'Escape';
if (keyboard && escPressed && modal.isTopModal()) {
  onEscapeKeyDown?.(e);
  ...
}

This would solve my particular problem, but more generally future-proof this library if and when browsers drop support for KeyboardEvent.keyCode.

Describe alternatives you've considered

Testing Library suggests patching the key events as a workaround:

const keyCodes = {
  Tab: 9,
}
function patchKeyEvent(e) {
  Object.defineProperty(e, 'keyCode', {
    get: () => keyCodes[e.code] ?? 0,
  })
}
document.addEventListener('keydown', patchKeyEvent, {capture: true})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant