Skip to content

Allow SWR mutation in useUser hook #2045

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@ianvs/prettier-plugin-sort-imports": "^4.3.1",
"@playwright/test": "^1.48.2",
"@stylistic/eslint-plugin-ts": "^3.1.0",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.8.6",
"@types/react": "*",
"@types/react-dom": "*",
Expand All @@ -45,6 +46,7 @@
"eslint-plugin-prettier": "^5.2.3",
"eslint-plugin-react": "^7.37.4",
"globals": "^15.14.0",
"jsdom": "^26.1.0",
"next": "15.2.3",
"prettier": "^3.3.3",
"typedoc": "^0.27.7",
Expand Down
407 changes: 402 additions & 5 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

149 changes: 149 additions & 0 deletions src/client/hooks/use-user.integration.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* @vitest-environment jsdom
*/

import React from "react";
import { act, renderHook, waitFor } from "@testing-library/react";
import * as swrModule from "swr";
import {
afterEach,
beforeEach,
describe,
expect,
it,
vi,
type MockInstance
} from "vitest";

import type { User } from "../../types/index.js";
import { useUser } from "./use-user.js";

// New test suite for integration testing with fetch and SWR cache
describe("useUser Integration with SWR Cache", () => {
const initialUser: User = {
sub: "initial_user_123",
name: "Initial User",
email: "[email protected]"
};
const updatedUser: User = {
sub: "updated_user_456",
name: "Updated User",
email: "[email protected]"
};

// Explicitly type fetchSpy using MockInstance and the global fetch signature
let fetchSpy: MockInstance<
(
input: RequestInfo | URL,
init?: RequestInit | undefined
) => Promise<Response>
>;

beforeEach(() => {
// Mock the global fetch
fetchSpy = vi.spyOn(global, "fetch");
});

afterEach(() => {
vi.restoreAllMocks(); // Restore original fetch implementation
});

it("should fetch initial user data and update after invalidate", async () => {
// Mock fetch to return initial data first
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify(initialUser), {
status: 200,
headers: { "Content-Type": "application/json" }
})
);

const wrapper = ({ children }: { children: React.ReactNode }) => (
<swrModule.SWRConfig value={{ provider: () => new Map() }}>
{children}
</swrModule.SWRConfig>
);

const { result } = renderHook(() => useUser(), { wrapper });

// Wait for the initial data to load
await waitFor(() => expect(result.current.isLoading).toBe(false));

// Assert initial state
expect(result.current.user).toEqual(initialUser);
expect(result.current.error).toBe(null);

// Mock fetch to return updated data for the next call
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify(updatedUser), {
status: 200,
headers: { "Content-Type": "application/json" }
})
);

// Call invalidate to trigger re-fetch
await act(async () => {
result.current.invalidate();
});
Comment on lines +83 to +86
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the user calls invalidate, it is going to call the URL again, is that correct? If yes, what is the reasoning for naming this invalidate, rather than refresh or so ?


// Wait for the hook to reflect the updated data
await waitFor(() => expect(result.current.user).toEqual(updatedUser));

// Assert updated state
expect(result.current.user).toEqual(updatedUser);
expect(result.current.error).toBe(null);
expect(result.current.isLoading).toBe(false);

// Verify fetch was called twice (initial load + invalidate)
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(fetchSpy).toHaveBeenCalledWith("/auth/profile");
});

it("should handle fetch error during invalidation", async () => {
// Mock fetch to return initial data first
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify(initialUser), {
status: 200,
headers: { "Content-Type": "application/json" }
})
);

const wrapper = ({ children }: { children: React.ReactNode }) => (
<swrModule.SWRConfig
value={{
provider: () => new Map(),
shouldRetryOnError: false,
dedupingInterval: 0
}}
>
{children}
</swrModule.SWRConfig>
);

const { result } = renderHook(() => useUser(), { wrapper });

// Wait for the initial data to load
await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(result.current.user).toEqual(initialUser);

// Mock fetch to return an error for the next call
const fetchError = new Error("Network Error");
fetchSpy.mockRejectedValueOnce(fetchError);

// Call invalidate to trigger re-fetch
await act(async () => {
result.current.invalidate();
});

// Wait for the hook to reflect the error state, user should still be the initial one before error
await waitFor(() => expect(result.current.error).not.toBeNull());

// Assert error state - SWR catches the rejection from fetch itself.
// Check for the message of the error we explicitly rejected with.
expect(result.current.user).toBeNull(); // Expect null now, not stale data
expect(result.current.error?.message).toBe(fetchError.message); // Correct assertion
expect(result.current.isLoading).toBe(false);

// Verify fetch was called twice
expect(fetchSpy).toHaveBeenCalledTimes(2);
});
});
21 changes: 11 additions & 10 deletions src/client/hooks/use-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,39 @@ import useSWR from "swr";
import type { User } from "../../types";

export function useUser() {
const { data, error, isLoading } = useSWR<User, Error, string>(
const { data, error, isLoading, mutate } = useSWR<User, Error, string>(
process.env.NEXT_PUBLIC_PROFILE_ROUTE || "/auth/profile",
(...args) =>
fetch(...args).then((res) => {
if (!res.ok) {
throw new Error("Unauthorized");
}

return res.json();
})
);

// if we have the user loaded via the provider, return it
if (data) {
if (error) {
return {
user: data,
user: null,
isLoading: false,
error: null
error,
invalidate: () => mutate()
};
}

if (error) {
if (data) {
return {
user: null,
user: data,
isLoading: false,
error
error: null,
invalidate: () => mutate()
};
}

return {
user: data,
isLoading,
error
error,
invalidate: () => mutate()
};
}
116 changes: 116 additions & 0 deletions src/client/hooks/use-user.unit.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import * as swrModule from "swr";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import type { User } from "../../types/index.js";
import { useUser } from "./use-user.js";

// Define mockMutate outside the mock factory so it can be referenced in tests
const mockMutate = vi.fn();

// Mock the SWR module, preserving original exports like SWRConfig
vi.mock("swr", async (importActual) => {
const actual = await importActual<typeof swrModule>();
return {
...actual,
default: vi.fn(() => ({
// Mock the default export (useSWR hook)
data: undefined,
error: undefined,
isLoading: true,
isValidating: false,
mutate: mockMutate
}))
};
});

describe("useUser", () => {
const mockUser: User = {
sub: "user_123",
name: "Test User",
email: "[email protected]"
};

beforeEach(() => {
// Clear mocks before each test
vi.clearAllMocks();
mockMutate.mockClear();
});

afterEach(() => {
// restoreAllMocks handles spies and mocks
vi.restoreAllMocks();
});

it("should return isLoading when no data or error", () => {
// Reset the global mock implementation for this specific test
vi.mocked(swrModule.default).mockImplementation(() => ({
data: undefined,
error: undefined,
isLoading: true,
isValidating: false,
mutate: mockMutate
}));
const result = useUser();

expect(result.isLoading).toBe(true);
expect(result.user).toBe(undefined);
expect(result.error).toBe(undefined);
expect(typeof result.invalidate).toBe("function");
});

it("should return user data when data is available", () => {
// Mock SWR default export (useSWR hook) to return user data for this test
vi.mocked(swrModule.default).mockImplementationOnce(() => ({
data: mockUser,
error: undefined,
isLoading: false,
isValidating: false,
mutate: mockMutate
}));

const result = useUser();

expect(result.isLoading).toBe(false);
expect(result.user).toBe(mockUser);
expect(result.error).toBe(null);
expect(typeof result.invalidate).toBe("function");
});

it("should return error when fetch fails", () => {
const mockError = new Error("Unauthorized");
// Mock SWR default export (useSWR hook) to return error for this test
vi.mocked(swrModule.default).mockImplementationOnce(() => ({
data: undefined,
error: mockError,
isLoading: false,
isValidating: false,
mutate: mockMutate
}));

const result = useUser();

expect(result.isLoading).toBe(false);
expect(result.user).toBe(null);
expect(result.error).toBe(mockError);
expect(typeof result.invalidate).toBe("function");
});

it("should call mutate when invalidate is called", () => {
// Mock SWR default export (useSWR hook) with mockMutate for invalidate testing
vi.mocked(swrModule.default).mockImplementationOnce(() => ({
data: mockUser,
error: undefined,
isLoading: false,
isValidating: false,
mutate: mockMutate
}));

const result = useUser();

// Call invalidate function
result.invalidate();

// Verify mutate was called
expect(mockMutate).toHaveBeenCalledTimes(1);
});
});
Loading
Loading