|
| 1 | +import { renderHook, act } from '@testing-library/react'; |
| 2 | + |
| 3 | +import { useSimulateProgress } from '../src'; |
| 4 | + |
| 5 | +// Mock timers |
| 6 | +jest.useFakeTimers(); |
| 7 | + |
| 8 | +describe('useSimulateProgress', () => { |
| 9 | + it('should update progress periodically and reach 100%', () => { |
| 10 | + const mockCallback = jest.fn(); |
| 11 | + const { result } = renderHook(() => |
| 12 | + useSimulateProgress(1000, mockCallback), |
| 13 | + ); |
| 14 | + |
| 15 | + // Initial progress should be 0 |
| 16 | + expect(result.current).toBe(0); |
| 17 | + |
| 18 | + // Fast-forward the timer, simulating time passing |
| 19 | + act(() => { |
| 20 | + jest.advanceTimersByTime(250); |
| 21 | + }); |
| 22 | + |
| 23 | + // Progress should update to 25% |
| 24 | + expect(result.current).toBe(25); |
| 25 | + |
| 26 | + act(() => { |
| 27 | + jest.advanceTimersByTime(500); // Fast-forward another 500ms |
| 28 | + }); |
| 29 | + |
| 30 | + // Progress should update to 75% |
| 31 | + expect(result.current).toBe(75); |
| 32 | + |
| 33 | + act(() => { |
| 34 | + jest.advanceTimersByTime(250); // Finish the remaining time |
| 35 | + }); |
| 36 | + |
| 37 | + // Progress should be 100%, and callback should be called |
| 38 | + expect(result.current).toBe(100); |
| 39 | + expect(mockCallback).toHaveBeenCalledTimes(1); |
| 40 | + }); |
| 41 | + |
| 42 | + it('should not call callback if progress is less than 100%', () => { |
| 43 | + const mockCallback = jest.fn(); |
| 44 | + const { result } = renderHook(() => |
| 45 | + useSimulateProgress(1000, mockCallback), |
| 46 | + ); |
| 47 | + |
| 48 | + // Fast-forward the timer to 50% |
| 49 | + act(() => { |
| 50 | + jest.advanceTimersByTime(500); // Fast-forward 500ms |
| 51 | + }); |
| 52 | + |
| 53 | + // Progress should be 50% |
| 54 | + expect(result.current).toBe(50); |
| 55 | + |
| 56 | + // Callback should not be called |
| 57 | + expect(mockCallback).not.toHaveBeenCalled(); |
| 58 | + }); |
| 59 | + |
| 60 | + test('should clear interval when unmounted', () => { |
| 61 | + const mockCallback = jest.fn(); |
| 62 | + const { result, unmount } = renderHook(() => |
| 63 | + useSimulateProgress(1000, mockCallback), |
| 64 | + ); |
| 65 | + |
| 66 | + // Fast-forward the timer halfway |
| 67 | + act(() => { |
| 68 | + jest.advanceTimersByTime(500); |
| 69 | + }); |
| 70 | + |
| 71 | + // Progress should be 50% |
| 72 | + expect(result.current).toBe(50); |
| 73 | + |
| 74 | + // Unmount the component |
| 75 | + unmount(); |
| 76 | + |
| 77 | + // Clear the timer, ensuring no further updates |
| 78 | + act(() => { |
| 79 | + jest.advanceTimersByTime(500); // Finish the remaining time |
| 80 | + }); |
| 81 | + |
| 82 | + // Progress should not update further |
| 83 | + expect(result.current).toBe(50); |
| 84 | + |
| 85 | + // Callback should not be called |
| 86 | + expect(mockCallback).not.toHaveBeenCalled(); |
| 87 | + }); |
| 88 | +}); |
0 commit comments