UNPKG

@amsterdam/design-system-react

Version:

All React components from the Amsterdam Design System. Use it to compose pages in your website or application.

80 lines (79 loc) 3.37 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; /** * @license EUPL-1.2+ * Copyright Gemeente Amsterdam */ import { fireEvent, render } from '@testing-library/react'; import { useRef } from 'react'; import { KeyboardKeys, useKeyboardFocus } from './useKeyboardFocus'; describe('use focus with arrows', () => { const onFocusOneMock = jest.fn(); const onFocusTwoMock = jest.fn(); const onFocusThreeMock = jest.fn(); const Component = ({ rotate = undefined }) => { const ref = useRef(null); const { keyDown } = useKeyboardFocus(ref, { rotating: rotate, }); return (_jsxs("div", { onKeyDown: keyDown, ref: ref, role: "menu", tabIndex: 0, children: [_jsx("button", { onFocus: onFocusOneMock, type: "button", children: "One" }), _jsx("button", { onFocus: onFocusTwoMock, type: "button", children: "Two" }), _jsx("button", { onFocus: onFocusThreeMock, type: "button", children: "Three" })] })); }; afterEach(() => { onFocusOneMock.mockReset(); onFocusTwoMock.mockReset(); onFocusThreeMock.mockReset(); }); it('sets focus when using arrow keys', () => { const { container } = render(_jsx(Component, {})); const firstChild = container.firstChild; expect(onFocusOneMock).not.toHaveBeenCalled(); // 4 times, so we can check if there are no other elements focused after reaching the last one Array.from(Array(4).keys()).forEach(() => { fireEvent.keyDown(firstChild, { key: KeyboardKeys.ArrowDown, }); }); expect(onFocusOneMock).toHaveBeenCalledTimes(1); expect(onFocusTwoMock).toHaveBeenCalledTimes(1); expect(onFocusThreeMock).toHaveBeenCalledTimes(1); // Same here Array.from(Array(4).keys()).forEach(() => { fireEvent.keyDown(firstChild, { key: KeyboardKeys.ArrowUp, }); }); expect(onFocusTwoMock).toHaveBeenCalledTimes(2); expect(onFocusOneMock).toHaveBeenCalledTimes(2); }); it('rotates focused elements', () => { const { container } = render(_jsx(Component, { rotate: true })); const firstChild = container.firstChild; Array.from(Array(9).keys()).forEach(() => { fireEvent.keyDown(firstChild, { key: KeyboardKeys.ArrowDown, }); }); expect(onFocusOneMock).toHaveBeenCalledTimes(3); Array.from(Array(9).keys()).forEach(() => { fireEvent.keyDown(firstChild, { key: KeyboardKeys.ArrowUp, }); }); expect(onFocusOneMock).toHaveBeenCalledTimes(6); }); it('sets focus to first element when using "Home" key', () => { const { container } = render(_jsx(Component, {})); const firstChild = container.firstChild; fireEvent.keyDown(firstChild, { key: KeyboardKeys.Home, }); expect(onFocusOneMock).toHaveBeenCalledTimes(1); }); it('sets focus to last element when using "End" key', () => { const { container } = render(_jsx(Component, {})); const firstChild = container.firstChild; fireEvent.keyDown(firstChild, { key: KeyboardKeys.End, }); expect(onFocusThreeMock).toHaveBeenCalledTimes(1); }); });