|
| 1 | +import { cleanup, render } from "@testing-library/react" |
| 2 | +import { QueryClient, QueryClientProvider } from "@tanstack/react-query" |
| 3 | +import { afterEach, describe, expect, it, vi } from "vitest" |
| 4 | + |
| 5 | +let mockUser: { id: number } | null = null |
| 6 | + |
| 7 | +vi.mock("@/lib/auth-context", () => ({ |
| 8 | + useAuth: () => ({ user: mockUser }), |
| 9 | +})) |
| 10 | + |
| 11 | +import { QueryAuthSync } from "@/components/query-auth-sync" |
| 12 | + |
| 13 | +function renderWith(qc: QueryClient) { |
| 14 | + return render( |
| 15 | + <QueryClientProvider client={qc}> |
| 16 | + <QueryAuthSync /> |
| 17 | + </QueryClientProvider>, |
| 18 | + ) |
| 19 | +} |
| 20 | + |
| 21 | +describe("QueryAuthSync", () => { |
| 22 | + afterEach(() => { |
| 23 | + cleanup() |
| 24 | + mockUser = null |
| 25 | + }) |
| 26 | + |
| 27 | + it("does not clear the cache on the first observation", () => { |
| 28 | + mockUser = { id: 1 } |
| 29 | + const qc = new QueryClient() |
| 30 | + const clear = vi.spyOn(qc, "clear") |
| 31 | + |
| 32 | + renderWith(qc) |
| 33 | + |
| 34 | + expect(clear).not.toHaveBeenCalled() |
| 35 | + }) |
| 36 | + |
| 37 | + it("clears the cache when the signed-in user changes", () => { |
| 38 | + mockUser = { id: 1 } |
| 39 | + const qc = new QueryClient() |
| 40 | + const clear = vi.spyOn(qc, "clear") |
| 41 | + const { rerender } = renderWith(qc) |
| 42 | + |
| 43 | + mockUser = { id: 2 } |
| 44 | + rerender( |
| 45 | + <QueryClientProvider client={qc}> |
| 46 | + <QueryAuthSync /> |
| 47 | + </QueryClientProvider>, |
| 48 | + ) |
| 49 | + |
| 50 | + expect(clear).toHaveBeenCalledTimes(1) |
| 51 | + }) |
| 52 | + |
| 53 | + it("clears the cache on sign-out (user becomes null) but not on an unchanged id", () => { |
| 54 | + mockUser = { id: 7 } |
| 55 | + const qc = new QueryClient() |
| 56 | + const clear = vi.spyOn(qc, "clear") |
| 57 | + const { rerender } = renderWith(qc) |
| 58 | + |
| 59 | + const redraw = () => |
| 60 | + rerender( |
| 61 | + <QueryClientProvider client={qc}> |
| 62 | + <QueryAuthSync /> |
| 63 | + </QueryClientProvider>, |
| 64 | + ) |
| 65 | + |
| 66 | + redraw() // same id -> no clear |
| 67 | + expect(clear).not.toHaveBeenCalled() |
| 68 | + |
| 69 | + mockUser = null |
| 70 | + redraw() // signed out -> clear |
| 71 | + expect(clear).toHaveBeenCalledTimes(1) |
| 72 | + }) |
| 73 | +}) |
0 commit comments