greena13 / react-hotkeys

Declarative hotkey and focus area management for React
https://github.com/greena13/react-hotkeys
ISC License
2.15k stars 161 forks source link

[BUG] Unable to test hotkeys with React Testing Library #282

Closed logicalmoody closed 4 years ago

logicalmoody commented 4 years ago

Describe the bug HotKeys do not fire when pressing keys via fireEvent in React Testing Library.

How are you using react hotkeys components? (HotKeys, GlobalHotKeys, IgnoreKeys etc) HotKeys

Expected behavior The react-hotkeys should be triggered by simulated keypresses from testing suites.

Reproduction Simple Code Sandbox displaying the issue. See src/demo.js and src/demo.test.js.

Are you willing and able to create a PR request to fix this issue? I don't currently have the bandwidth.

logicalmoody commented 4 years ago

Update: I managed to solve this problem by calling .focus() on the HotKeys handler which I get via a test ID.

Here is the test file snippet:

getByTestId("hotkeys-id").focus();
fireEvent.keyDown(getByTestId("hotkeys-id"), {
  key: "ArrowUp"
});

and the JSX from the component:

<HotKeys keyMap={{ UP: "up", DOWN: "down" }}>
  <HotKeys
    handlers={{
      UP: () => {
        setMyKey("UP");
      },
      DOWN: () => {
        setMyKey("DOWN");
      }
    }}
    data-testid="hotkeys-id"
  >
    <h1>Hello CodeSandbox</h1>
    <p>You have pressed: {myKey}</p>
  </HotKeys>
</HotKeys>

Link to the full solution sandbox for anyone else who is interested.