|
| 1 | +import { useCurrentTime } from '../lib' // Adjust the import path as needed |
| 2 | +import { act, renderHook } from '@testing-library/react' |
| 3 | + |
| 4 | +describe('useCurrentTime Hook', () => { |
| 5 | + it('should return the current time in milliseconds initially', () => { |
| 6 | + const initialTime = Date.now() |
| 7 | + const { result } = renderHook(() => useCurrentTime()) |
| 8 | + expect(result.current).toBeGreaterThanOrEqual(initialTime) |
| 9 | + expect(result.current).toBeLessThanOrEqual(initialTime + 50) // Allow for a small margin |
| 10 | + }) |
| 11 | + |
| 12 | + it('should update the time after the default refresh period (1000ms)', () => { |
| 13 | + jest.useFakeTimers() // Enable Jest's fake timers |
| 14 | + const { result } = renderHook(() => useCurrentTime()) |
| 15 | + const initialTime = result.current |
| 16 | + |
| 17 | + act(() => { |
| 18 | + jest.advanceTimersByTime(1000) // Advance the timers by the default refresh period |
| 19 | + }) |
| 20 | + |
| 21 | + const nextSecond = Math.ceil((initialTime + 1) / 1000) * 1000 // Round to the next second |
| 22 | + expect(result.current).toBeGreaterThanOrEqual(nextSecond) |
| 23 | + expect(result.current).toBeLessThanOrEqual(nextSecond + 50) // Allow for a small margin |
| 24 | + }) |
| 25 | + |
| 26 | + it('should update the time after a custom refresh period', () => { |
| 27 | + jest.useFakeTimers() // Enable Jest's fake timers |
| 28 | + const refreshPeriod = 500 |
| 29 | + const { result } = renderHook(() => useCurrentTime(refreshPeriod)) |
| 30 | + const initialTime = result.current |
| 31 | + |
| 32 | + act(() => { |
| 33 | + jest.advanceTimersByTime(refreshPeriod) |
| 34 | + }) |
| 35 | + |
| 36 | + const nextInterval = Math.ceil((initialTime + 1) / refreshPeriod) * refreshPeriod // Round to the next refreshPeriod |
| 37 | + expect(result.current).toBeGreaterThanOrEqual(nextInterval - 50) |
| 38 | + expect(result.current).toBeLessThanOrEqual(nextInterval + 50) // Allow for a small margin |
| 39 | + }) |
| 40 | + |
| 41 | + it('should clear the timeout on unmount', () => { |
| 42 | + const { unmount } = renderHook(() => useCurrentTime()) |
| 43 | + const mockClearTimeout = jest.spyOn(global, 'clearTimeout') |
| 44 | + |
| 45 | + unmount() |
| 46 | + |
| 47 | + expect(mockClearTimeout).toHaveBeenCalledTimes(1) |
| 48 | + // You could also assert that the timeout ID stored in the ref was passed to clearTimeout |
| 49 | + }) |
| 50 | +}) |
0 commit comments