|
| 1 | +import { act, renderHook } from '@testing-library/react'; |
| 2 | + |
| 3 | +import { renderHookServer } from '@/tests'; |
| 4 | + |
| 5 | +import { useWindowFocus } from './useWindowFocus'; |
| 6 | + |
| 7 | +it('Should use window focus', () => { |
| 8 | + const { result } = renderHook(useWindowFocus); |
| 9 | + |
| 10 | + expect(result.current).toBe(false); |
| 11 | +}); |
| 12 | + |
| 13 | +it('Should use window focus on server side', () => { |
| 14 | + const { result } = renderHookServer(useWindowFocus); |
| 15 | + |
| 16 | + expect(result.current).toBe(false); |
| 17 | +}); |
| 18 | + |
| 19 | +it('Should update state on focus and blur events', () => { |
| 20 | + const { result } = renderHook(useWindowFocus); |
| 21 | + |
| 22 | + expect(result.current).toBe(false); |
| 23 | + |
| 24 | + act(() => { |
| 25 | + window.dispatchEvent(new Event('focus')); |
| 26 | + }); |
| 27 | + |
| 28 | + expect(result.current).toBe(true); |
| 29 | + |
| 30 | + act(() => { |
| 31 | + window.dispatchEvent(new Event('blur')); |
| 32 | + }); |
| 33 | + |
| 34 | + expect(result.current).toBe(false); |
| 35 | +}); |
| 36 | + |
| 37 | +it('Should cleanup on unmount', () => { |
| 38 | + const addEventListenerSpy = vi.spyOn(window, 'addEventListener'); |
| 39 | + const removeEventListenerSpy = vi.spyOn(window, 'removeEventListener'); |
| 40 | + |
| 41 | + const { unmount } = renderHook(useWindowFocus); |
| 42 | + |
| 43 | + expect(addEventListenerSpy).toHaveBeenCalledWith('focus', expect.any(Function)); |
| 44 | + expect(addEventListenerSpy).toHaveBeenCalledWith('blur', expect.any(Function)); |
| 45 | + |
| 46 | + unmount(); |
| 47 | + |
| 48 | + expect(removeEventListenerSpy).toHaveBeenCalledWith('focus', expect.any(Function)); |
| 49 | + expect(removeEventListenerSpy).toHaveBeenCalledWith('blur', expect.any(Function)); |
| 50 | +}); |
| 51 | + |
| 52 | +it('Should not update state after unmount', () => { |
| 53 | + const { result, unmount } = renderHook(useWindowFocus); |
| 54 | + |
| 55 | + unmount(); |
| 56 | + |
| 57 | + act(() => { |
| 58 | + window.dispatchEvent(new Event('focus')); |
| 59 | + }); |
| 60 | + |
| 61 | + expect(result.current).toBe(false); |
| 62 | +}); |
0 commit comments