Skip to content
Advertisement

How can I test `onKeyDown` prop in React with @testing-library/user-event version 14?

I am creating a list of menu items using React. I want to test that when a user clicks or presses enter on an item, the onSelect prop is called.

Here is a simplified version of my component:

JavaScript

Here is my test:

JavaScript

When running the tests I get the following output:

JavaScript

How can I test that onSelect was called when the user presses Enter on the item component?

Advertisement

Answer

https://testing-library.com/docs/user-event/keyboard

The keyboard API allows to simulate interactions with a keyboard. It accepts a string describing the key actions.

JavaScript

KeyboardEvent.keyCode is deprecated.
Therefore we don’t support it and encourage you to update your implementation to use non-deprecated features like KeyboardEvent.key or KeyboardEvent.code.

https://codesandbox.io/s/crazy-snyder-gurptu?file=/src/Item.test.js

Advertisement