|
| 1 | +import { renderHook, act } from '@testing-library/react-hooks'; |
| 2 | +import useWindowFocus from '../src/useWindowFocus'; |
| 3 | + |
| 4 | +describe('useWindowFocus', () => { |
| 5 | + it('should be defined', () => { |
| 6 | + expect(useWindowFocus).toBeDefined(); |
| 7 | + }); |
| 8 | + |
| 9 | + it('should return false initially', () => { |
| 10 | + const { result } = renderHook(() => useWindowFocus()); |
| 11 | + |
| 12 | + expect(result.current).toBe(false); |
| 13 | + }); |
| 14 | + |
| 15 | + it('should return true initially when defaultState is true', () => { |
| 16 | + // Mock document.hasFocus() to return true |
| 17 | + const hasFocusSpy = jest.spyOn(document, 'hasFocus').mockReturnValue(true); |
| 18 | + |
| 19 | + const { result } = renderHook(() => useWindowFocus(true)); |
| 20 | + |
| 21 | + expect(result.current).toBe(true); |
| 22 | + |
| 23 | + hasFocusSpy.mockRestore(); |
| 24 | + }); |
| 25 | + |
| 26 | + it('should return false initially when initialState is false', () => { |
| 27 | + const { result } = renderHook(() => useWindowFocus(false)); |
| 28 | + |
| 29 | + expect(result.current).toBe(false); |
| 30 | + }); |
| 31 | + |
| 32 | + it('should return true when window receives focus', () => { |
| 33 | + const { result } = renderHook(() => useWindowFocus()); |
| 34 | + |
| 35 | + act(() => { |
| 36 | + window.dispatchEvent(new Event('focus')); |
| 37 | + }); |
| 38 | + |
| 39 | + expect(result.current).toBe(true); |
| 40 | + }); |
| 41 | + |
| 42 | + it('should return false when window loses focus', () => { |
| 43 | + const { result } = renderHook(() => useWindowFocus()); |
| 44 | + |
| 45 | + act(() => { |
| 46 | + window.dispatchEvent(new Event('focus')); |
| 47 | + }); |
| 48 | + expect(result.current).toBe(true); |
| 49 | + |
| 50 | + act(() => { |
| 51 | + window.dispatchEvent(new Event('blur')); |
| 52 | + }); |
| 53 | + expect(result.current).toBe(false); |
| 54 | + }); |
| 55 | + |
| 56 | + it('should add event listeners on mount', () => { |
| 57 | + const addEventListenerSpy = jest.spyOn(window, 'addEventListener'); |
| 58 | + |
| 59 | + renderHook(() => useWindowFocus()); |
| 60 | + |
| 61 | + expect(addEventListenerSpy).toHaveBeenCalledWith('focus', expect.any(Function)); |
| 62 | + expect(addEventListenerSpy).toHaveBeenCalledWith('blur', expect.any(Function)); |
| 63 | + |
| 64 | + addEventListenerSpy.mockRestore(); |
| 65 | + }); |
| 66 | + |
| 67 | + it('should remove event listeners on unmount', () => { |
| 68 | + const removeEventListenerSpy = jest.spyOn(window, 'removeEventListener'); |
| 69 | + |
| 70 | + const { unmount } = renderHook(() => useWindowFocus()); |
| 71 | + unmount(); |
| 72 | + |
| 73 | + expect(removeEventListenerSpy).toHaveBeenCalledWith('focus', expect.any(Function)); |
| 74 | + expect(removeEventListenerSpy).toHaveBeenCalledWith('blur', expect.any(Function)); |
| 75 | + |
| 76 | + removeEventListenerSpy.mockRestore(); |
| 77 | + }); |
| 78 | +}); |
0 commit comments