|
| 1 | +import React, { useRef, useEffect } from 'react'; |
| 2 | +import { render, fireEvent } from '@testing-library/react'; |
| 3 | +import useModalClose from './useModalClose'; |
| 4 | +import useKeyDownHandlers from './useKeyDownHandlers'; |
| 5 | + |
| 6 | +jest.mock('./useKeyDownHandlers'); |
| 7 | + |
| 8 | +describe('useModalClose', () => { |
| 9 | + let onClose: jest.Mock; |
| 10 | + |
| 11 | + beforeEach(() => { |
| 12 | + onClose = jest.fn(); |
| 13 | + jest.clearAllMocks(); |
| 14 | + }); |
| 15 | + |
| 16 | + function TestModal({ handleClose }: { handleClose: () => void }) { |
| 17 | + const ref = useModalClose(handleClose); |
| 18 | + return ( |
| 19 | + <div> |
| 20 | + <div data-testid="outside">Outside</div> |
| 21 | + <div |
| 22 | + data-testid="modal" |
| 23 | + ref={ref as React.RefObject<HTMLDivElement>} |
| 24 | + tabIndex={-1} |
| 25 | + style={{ border: '1px solid black' }} |
| 26 | + > |
| 27 | + Modal content |
| 28 | + </div> |
| 29 | + </div> |
| 30 | + ); |
| 31 | + } |
| 32 | + |
| 33 | + function rerender() { |
| 34 | + return render(<TestModal handleClose={onClose} />); |
| 35 | + } |
| 36 | + |
| 37 | + it('calls onClose when clicking outside the modal', () => { |
| 38 | + const { getByTestId } = rerender(); |
| 39 | + |
| 40 | + fireEvent.click(getByTestId('outside')); |
| 41 | + |
| 42 | + expect(onClose).toHaveBeenCalled(); |
| 43 | + }); |
| 44 | + |
| 45 | + it('does not call onClose when clicking inside the modal', () => { |
| 46 | + const { getByTestId } = rerender(); |
| 47 | + |
| 48 | + fireEvent.click(getByTestId('modal')); |
| 49 | + |
| 50 | + expect(onClose).not.toHaveBeenCalled(); |
| 51 | + }); |
| 52 | + |
| 53 | + it('returns a ref that is focused on mount', () => { |
| 54 | + const { getByTestId } = rerender(); |
| 55 | + const modal = getByTestId('modal'); |
| 56 | + |
| 57 | + expect(document.activeElement).toBe(modal); |
| 58 | + }); |
| 59 | + |
| 60 | + it('calls useKeyDownHandlers with escape handler', () => { |
| 61 | + rerender(); |
| 62 | + |
| 63 | + expect(useKeyDownHandlers).toHaveBeenCalledWith({ escape: onClose }); |
| 64 | + }); |
| 65 | +}); |
0 commit comments