|
| 1 | +import { renderHook } from "@testing-library/react"; |
| 2 | +import { useUpdateEffect } from "./useUpdateEffect"; |
| 3 | + |
| 4 | +describe("useUpdateEffect", () => { |
| 5 | + it("should not run the effect on the first render", () => { |
| 6 | + const effect = vi.fn(); |
| 7 | + |
| 8 | + renderHook(() => useUpdateEffect(effect)); |
| 9 | + |
| 10 | + // The effect should not have been called yet |
| 11 | + expect(effect).not.toHaveBeenCalled(); |
| 12 | + }); |
| 13 | + |
| 14 | + it("should run the effect on subsequent renders", () => { |
| 15 | + const effect = vi.fn(); |
| 16 | + |
| 17 | + const { rerender } = renderHook(() => { |
| 18 | + useUpdateEffect(effect); |
| 19 | + }); |
| 20 | + |
| 21 | + rerender(); |
| 22 | + |
| 23 | + // The effect should have been called once |
| 24 | + expect(effect).toHaveBeenCalledTimes(1); |
| 25 | + }); |
| 26 | + |
| 27 | + it("should run the effect when dependencies change", () => { |
| 28 | + const effect = vi.fn(); |
| 29 | + |
| 30 | + const { rerender } = renderHook((dependency: string = "initial_dependency") => |
| 31 | + useUpdateEffect(effect, [dependency]) |
| 32 | + ); |
| 33 | + |
| 34 | + rerender("updated_dependency"); |
| 35 | + |
| 36 | + // The effect should have been called once |
| 37 | + expect(effect).toHaveBeenCalledTimes(1); |
| 38 | + }); |
| 39 | + |
| 40 | + it("should not run the effect if dependencies do not change", () => { |
| 41 | + const effect = vi.fn(); |
| 42 | + |
| 43 | + const { rerender } = renderHook((dependency: string = "same_dependency") => |
| 44 | + useUpdateEffect(effect, [dependency]) |
| 45 | + ); |
| 46 | + |
| 47 | + rerender("same_dependency"); |
| 48 | + |
| 49 | + // The effect should not have been called again |
| 50 | + expect(effect).toHaveBeenCalledTimes(0); |
| 51 | + }); |
| 52 | +}); |
0 commit comments