|
| 1 | +import { act, renderHook } from "@testing-library/react"; |
| 2 | +import { afterEach, beforeAll } from "vitest"; |
| 3 | +import { useDebouncedValue } from "../hooks/useDebouncedValue"; |
| 4 | + |
| 5 | +beforeAll(() => { |
| 6 | + vi.useFakeTimers(); |
| 7 | +}); |
| 8 | + |
| 9 | +afterEach(() => { |
| 10 | + // Should be no pending timers after each test |
| 11 | + expect(vi.getTimerCount()).toBe(0); |
| 12 | +}); |
| 13 | + |
| 14 | +test("should update the value after the delay", async () => { |
| 15 | + const initialValue = "hello"; |
| 16 | + const { result } = renderHook(() => useDebouncedValue(initialValue, 500)); |
| 17 | + |
| 18 | + expect(result.current[0]).toBe(initialValue); |
| 19 | + result.current[1]("world"); |
| 20 | + act(() => { |
| 21 | + vi.runAllTimers(); |
| 22 | + }); |
| 23 | + |
| 24 | + expect(result.current[0]).toBe("world"); |
| 25 | +}); |
| 26 | + |
| 27 | +test("should skip old value", async () => { |
| 28 | + const initialValue = "hello"; |
| 29 | + const { result } = renderHook(() => useDebouncedValue(initialValue, 500)); |
| 30 | + |
| 31 | + expect(result.current[0]).toBe(initialValue); |
| 32 | + result.current[1]("new"); |
| 33 | + act(() => { |
| 34 | + vi.advanceTimersByTime(250); |
| 35 | + }); |
| 36 | + |
| 37 | + expect(result.current[0]).toBe(initialValue); |
| 38 | + |
| 39 | + result.current[1]("world"); |
| 40 | + act(() => { |
| 41 | + vi.runAllTimers(); |
| 42 | + }); |
| 43 | + |
| 44 | + expect(result.current[0]).toBe("world"); |
| 45 | +}); |
| 46 | + |
| 47 | +test("should update if 'initial value' is changed", async () => { |
| 48 | + const { result, rerender } = renderHook((initialValue = "hello") => |
| 49 | + useDebouncedValue(initialValue, 500), |
| 50 | + ); |
| 51 | + |
| 52 | + expect(result.current[0]).toBe("hello"); |
| 53 | + rerender("world"); |
| 54 | + |
| 55 | + act(() => { |
| 56 | + // Should have triggered the update, when the value changes |
| 57 | + expect(vi.getTimerCount()).toBe(1); |
| 58 | + vi.runAllTimers(); |
| 59 | + }); |
| 60 | + |
| 61 | + expect(result.current[0]).toBe("world"); |
| 62 | +}); |
| 63 | + |
| 64 | +test("should update the value immediately if leading is true", async () => { |
| 65 | + const initialValue = "hello"; |
| 66 | + const { result } = renderHook(() => |
| 67 | + useDebouncedValue(initialValue, 500, { leading: true }), |
| 68 | + ); |
| 69 | + |
| 70 | + expect(result.current[0]).toBe(initialValue); |
| 71 | + act(() => { |
| 72 | + result.current[1]("world"); |
| 73 | + }); |
| 74 | + expect(result.current[0]).toBe("world"); |
| 75 | + |
| 76 | + act(() => { |
| 77 | + vi.runAllTimers(); |
| 78 | + }); |
| 79 | +}); |
0 commit comments