|
| 1 | +/** |
| 2 | + * @vitest-environment jsdom |
| 3 | + */ |
| 4 | + |
| 5 | +import React from "react"; |
| 6 | +import { act, renderHook, waitFor } from "@testing-library/react"; |
| 7 | +import * as swrModule from "swr"; |
| 8 | +import { |
| 9 | + afterEach, |
| 10 | + beforeEach, |
| 11 | + describe, |
| 12 | + expect, |
| 13 | + it, |
| 14 | + vi, |
| 15 | + type MockInstance |
| 16 | +} from "vitest"; |
| 17 | + |
| 18 | +import type { User } from "../../types/index.js"; |
| 19 | +import { useUser } from "./use-user.js"; |
| 20 | + |
| 21 | +// New test suite for integration testing with fetch and SWR cache |
| 22 | +describe("useUser Integration with SWR Cache", () => { |
| 23 | + const initialUser: User = { |
| 24 | + sub: "initial_user_123", |
| 25 | + name: "Initial User", |
| 26 | + email: "initial@example.com" |
| 27 | + }; |
| 28 | + const updatedUser: User = { |
| 29 | + sub: "updated_user_456", |
| 30 | + name: "Updated User", |
| 31 | + email: "updated@example.com" |
| 32 | + }; |
| 33 | + |
| 34 | + // Explicitly type fetchSpy using MockInstance and the global fetch signature |
| 35 | + let fetchSpy: MockInstance< |
| 36 | + ( |
| 37 | + input: RequestInfo | URL, |
| 38 | + init?: RequestInit | undefined |
| 39 | + ) => Promise<Response> |
| 40 | + >; |
| 41 | + |
| 42 | + beforeEach(() => { |
| 43 | + // Mock the global fetch |
| 44 | + fetchSpy = vi.spyOn(global, "fetch"); |
| 45 | + }); |
| 46 | + |
| 47 | + afterEach(() => { |
| 48 | + vi.restoreAllMocks(); // Restore original fetch implementation |
| 49 | + }); |
| 50 | + |
| 51 | + it("should fetch initial user data and update after invalidate", async () => { |
| 52 | + // Mock fetch to return initial data first |
| 53 | + fetchSpy.mockResolvedValueOnce( |
| 54 | + new Response(JSON.stringify(initialUser), { |
| 55 | + status: 200, |
| 56 | + headers: { "Content-Type": "application/json" } |
| 57 | + }) |
| 58 | + ); |
| 59 | + |
| 60 | + const wrapper = ({ children }: { children: React.ReactNode }) => ( |
| 61 | + <swrModule.SWRConfig value={{ provider: () => new Map() }}> |
| 62 | + {children} |
| 63 | + </swrModule.SWRConfig> |
| 64 | + ); |
| 65 | + |
| 66 | + const { result } = renderHook(() => useUser(), { wrapper }); |
| 67 | + |
| 68 | + // Wait for the initial data to load |
| 69 | + await waitFor(() => expect(result.current.isLoading).toBe(false)); |
| 70 | + |
| 71 | + // Assert initial state |
| 72 | + expect(result.current.user).toEqual(initialUser); |
| 73 | + expect(result.current.error).toBe(null); |
| 74 | + |
| 75 | + // Mock fetch to return updated data for the next call |
| 76 | + fetchSpy.mockResolvedValueOnce( |
| 77 | + new Response(JSON.stringify(updatedUser), { |
| 78 | + status: 200, |
| 79 | + headers: { "Content-Type": "application/json" } |
| 80 | + }) |
| 81 | + ); |
| 82 | + |
| 83 | + // Call invalidate to trigger re-fetch |
| 84 | + await act(async () => { |
| 85 | + result.current.invalidate(); |
| 86 | + }); |
| 87 | + |
| 88 | + // Wait for the hook to reflect the updated data |
| 89 | + await waitFor(() => expect(result.current.user).toEqual(updatedUser)); |
| 90 | + |
| 91 | + // Assert updated state |
| 92 | + expect(result.current.user).toEqual(updatedUser); |
| 93 | + expect(result.current.error).toBe(null); |
| 94 | + expect(result.current.isLoading).toBe(false); |
| 95 | + |
| 96 | + // Verify fetch was called twice (initial load + invalidate) |
| 97 | + expect(fetchSpy).toHaveBeenCalledTimes(2); |
| 98 | + expect(fetchSpy).toHaveBeenCalledWith("/auth/profile"); |
| 99 | + }); |
| 100 | + |
| 101 | + it("should handle fetch error during invalidation", async () => { |
| 102 | + // Mock fetch to return initial data first |
| 103 | + fetchSpy.mockResolvedValueOnce( |
| 104 | + new Response(JSON.stringify(initialUser), { |
| 105 | + status: 200, |
| 106 | + headers: { "Content-Type": "application/json" } |
| 107 | + }) |
| 108 | + ); |
| 109 | + |
| 110 | + const wrapper = ({ children }: { children: React.ReactNode }) => ( |
| 111 | + <swrModule.SWRConfig |
| 112 | + value={{ |
| 113 | + provider: () => new Map(), |
| 114 | + shouldRetryOnError: false, |
| 115 | + dedupingInterval: 0 |
| 116 | + }} |
| 117 | + > |
| 118 | + {children} |
| 119 | + </swrModule.SWRConfig> |
| 120 | + ); |
| 121 | + |
| 122 | + const { result } = renderHook(() => useUser(), { wrapper }); |
| 123 | + |
| 124 | + // Wait for the initial data to load |
| 125 | + await waitFor(() => expect(result.current.isLoading).toBe(false)); |
| 126 | + expect(result.current.user).toEqual(initialUser); |
| 127 | + |
| 128 | + // Mock fetch to return an error for the next call |
| 129 | + const fetchError = new Error("Network Error"); |
| 130 | + fetchSpy.mockRejectedValueOnce(fetchError); |
| 131 | + |
| 132 | + // Call invalidate to trigger re-fetch |
| 133 | + await act(async () => { |
| 134 | + result.current.invalidate(); |
| 135 | + }); |
| 136 | + |
| 137 | + // Wait for the hook to reflect the error state, user should still be the initial one before error |
| 138 | + await waitFor(() => expect(result.current.error).not.toBeNull()); |
| 139 | + |
| 140 | + // Assert error state - SWR catches the rejection from fetch itself. |
| 141 | + // Check for the message of the error we explicitly rejected with. |
| 142 | + expect(result.current.user).toBeNull(); // Expect null now, not stale data |
| 143 | + expect(result.current.error?.message).toBe(fetchError.message); // Correct assertion |
| 144 | + expect(result.current.isLoading).toBe(false); |
| 145 | + |
| 146 | + // Verify fetch was called twice |
| 147 | + expect(fetchSpy).toHaveBeenCalledTimes(2); |
| 148 | + }); |
| 149 | +}); |
0 commit comments