import React, { FunctionComponent } from "react"; import { cleanup, testHook, render, fireEvent } from "react-testing-library"; import { useKeyboardFocusEventHandler } from "../useKeyboardFocus"; describe("useKeyboardFocusEventHandler", () => { const onKeyboardFocus = jest.fn(); const Test: FunctionComponent = ({ onKeyDown, onKeyboardFocus, ...config }) => { const { handlers: { onKeyboardFocus: _, ...handlers }, } = useKeyboardFocusEventHandler({ ...config, onKeyboardFocus, handlers: { onKeyDown, }, }); return ( ); }; Test.defaultProps = { onKeyboardFocus, }; afterEach(() => { cleanup(); onKeyboardFocus.mockClear(); }); it("should return the correct object", () => { let value; testHook( () => (value = useKeyboardFocusEventHandler({ onKeyboardFocus, handlers: {}, })) ); expect(value).toEqual({ handlers: expect.objectContaining({ onKeyDown: expect.any(Function), }), }); }); it("should call the onKeyDown option correctly", () => { const onKeyDown = jest.fn(); const { getByRole } = render(); const menu = getByRole("menu"); expect(onKeyDown).not.toBeCalled(); fireEvent.keyDown(menu); expect(onKeyDown).toBeCalled(); }); it("should not trigger the onKeyboardFocus when there is not a valid keyboard key mapping", () => { const { getByRole } = render( ); const menu = getByRole("menu"); fireEvent.keyDown(menu); fireEvent.keyDown(menu, { key: "Tab" }); fireEvent.keyDown(menu, { key: "Tab", shiftKey: true }); expect(onKeyboardFocus).not.toBeCalled(); }); });