|
7 | 7 | */ |
8 | 8 |
|
9 | 9 | import { describe, it, expect, vi } from "vitest"; |
| 10 | +import { renderHook, act } from "@testing-library/react"; |
| 11 | +import { useResizeWidth } from "./hooks"; |
10 | 12 | import { |
11 | 13 | linearScale, |
12 | 14 | niceTicks, |
@@ -871,3 +873,66 @@ describe("sankeyLinkPath", () => { |
871 | 873 | expect(path).toContain("C"); |
872 | 874 | }); |
873 | 875 | }); |
| 876 | + |
| 877 | +// --------------------------------------------------------------------------- |
| 878 | +// useResizeWidth |
| 879 | +// --------------------------------------------------------------------------- |
| 880 | + |
| 881 | +describe("useResizeWidth", () => { |
| 882 | + it("returns 0 when called with no arguments", () => { |
| 883 | + const { result } = renderHook(() => useResizeWidth()); |
| 884 | + expect(result.current.width).toBe(0); |
| 885 | + expect(typeof result.current.attachRef).toBe("function"); |
| 886 | + }); |
| 887 | + |
| 888 | + it("returns initialWidth when no observer has fired", () => { |
| 889 | + const { result } = renderHook(() => useResizeWidth(800)); |
| 890 | + expect(result.current.width).toBe(800); |
| 891 | + }); |
| 892 | + |
| 893 | + it("returns initialWidth for various values", () => { |
| 894 | + const { result: r1 } = renderHook(() => useResizeWidth(1024)); |
| 895 | + expect(r1.current.width).toBe(1024); |
| 896 | + |
| 897 | + const { result: r2 } = renderHook(() => useResizeWidth(320)); |
| 898 | + expect(r2.current.width).toBe(320); |
| 899 | + }); |
| 900 | + |
| 901 | + it("returns 0 when initialWidth is 0", () => { |
| 902 | + const { result } = renderHook(() => useResizeWidth(0)); |
| 903 | + expect(result.current.width).toBe(0); |
| 904 | + }); |
| 905 | + |
| 906 | + it("observer measurement takes over from initialWidth", () => { |
| 907 | + let observerCallback: ResizeObserverCallback; |
| 908 | + const mockObserver = { |
| 909 | + observe: vi.fn(), |
| 910 | + disconnect: vi.fn(), |
| 911 | + unobserve: vi.fn(), |
| 912 | + }; |
| 913 | + vi.stubGlobal( |
| 914 | + "ResizeObserver", |
| 915 | + vi.fn((cb: ResizeObserverCallback) => { |
| 916 | + observerCallback = cb; |
| 917 | + return mockObserver; |
| 918 | + }), |
| 919 | + ); |
| 920 | + |
| 921 | + const { result } = renderHook(() => useResizeWidth(800)); |
| 922 | + expect(result.current.width).toBe(800); |
| 923 | + |
| 924 | + const fakeNode = { clientWidth: 0 } as HTMLDivElement; |
| 925 | + act(() => result.current.attachRef(fakeNode)); |
| 926 | + |
| 927 | + act(() => { |
| 928 | + observerCallback( |
| 929 | + [{ contentRect: { width: 600 } }] as ResizeObserverEntry[], |
| 930 | + {} as ResizeObserver, |
| 931 | + ); |
| 932 | + }); |
| 933 | + |
| 934 | + expect(result.current.width).toBe(600); |
| 935 | + |
| 936 | + vi.unstubAllGlobals(); |
| 937 | + }); |
| 938 | +}); |
0 commit comments