(updated ) by

Testing library with Mousetrap

Mousetrap is a library for handling keyboard events. testing-library is a tool to help testing React components. If you use both of these you may find it difficult to trigger mousetrap events inside components. The suggested userEvent.keyboard does not seem to trigger it.

const X = ({ undo }) => {
	useEffect(() => {
		const mt = new Mousetrap();
		mt.bind('ctrl+z', undo)

		return function cleanup() {
			mt.unbind('ctrl+z')
		}
	})
	return <div data-testid="yo"></>
}
test("that undo fires", () => {
  const undo = jest.fn();
  render(<X undo={undo} />);

  userEvent.keyboard("{Ctrl>}z{/Ctrl}");

  expect(undo).toHaveBeenCalled();
});

This test fails as not triggering the event.

The current solution is to use fireEvent instead.

test("that undo fires", () => {
  const undo = jest.fn();
  render(<X undo={undo} />);

  fireEvent.keyDown(screen.getByTestId("yo"), {
    ctrlKey: true,
    key: "z",
    which: 90,
    code: "KeyZ",
  });

  expect(undo).toHaveBeenCalled();
});