|
| 1 | +import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react'; |
| 2 | + |
| 3 | +import { useHover } from './useHover'; |
| 4 | + |
| 5 | +describe('useHover', () => { |
| 6 | + afterEach(cleanup); |
| 7 | + |
| 8 | + const mockRef = { |
| 9 | + current: document.createElement('div') |
| 10 | + }; |
| 11 | + |
| 12 | + it('should return ref and hovering state without target element overload', () => { |
| 13 | + const { result } = renderHook(() => useHover({})); |
| 14 | + const [ref, hovering] = result.current; |
| 15 | + |
| 16 | + expect(ref.current).toBe(null); |
| 17 | + expect(hovering).toBe(false); |
| 18 | + }); |
| 19 | + |
| 20 | + it('should update hovering state when mouse enters and leaves the target', () => { |
| 21 | + const { result } = renderHook(() => useHover(mockRef)); |
| 22 | + |
| 23 | + expect(result.current).toBe(false); |
| 24 | + |
| 25 | + act(() => fireEvent.mouseEnter(mockRef.current)); |
| 26 | + expect(result.current).toBe(true); |
| 27 | + |
| 28 | + act(() => fireEvent.mouseLeave(mockRef.current)); |
| 29 | + expect(result.current).toBe(false); |
| 30 | + }); |
| 31 | + |
| 32 | + it('should call onEntry and onLeave callback functions when provided', () => { |
| 33 | + const onEntry = vi.fn(); |
| 34 | + const onLeave = vi.fn(); |
| 35 | + |
| 36 | + renderHook(() => useHover(mockRef, { onEntry, onLeave })); |
| 37 | + |
| 38 | + act(() => fireEvent.mouseEnter(mockRef.current)); |
| 39 | + expect(onEntry).toHaveBeenCalledTimes(1); |
| 40 | + |
| 41 | + act(() => fireEvent.mouseLeave(mockRef.current)); |
| 42 | + expect(onLeave).toHaveBeenCalledTimes(1); |
| 43 | + }); |
| 44 | + |
| 45 | + it('should work properly without specifying a target element overload', () => { |
| 46 | + const MockComponent = () => { |
| 47 | + const [ref, isHovering] = useHover({}); |
| 48 | + |
| 49 | + return ( |
| 50 | + <div data-testid='target' ref={ref as React.RefObject<HTMLDivElement>}> |
| 51 | + {isHovering ? 'true' : 'false'} |
| 52 | + </div> |
| 53 | + ); |
| 54 | + }; |
| 55 | + |
| 56 | + render(<MockComponent />); |
| 57 | + const target = screen.getByTestId('target'); |
| 58 | + |
| 59 | + expect(target).toHaveTextContent('false'); |
| 60 | + |
| 61 | + fireEvent.mouseEnter(target); |
| 62 | + expect(target).toHaveTextContent('true'); |
| 63 | + |
| 64 | + fireEvent.mouseLeave(target); |
| 65 | + expect(target).toHaveTextContent('false'); |
| 66 | + }); |
| 67 | +}); |
0 commit comments