-
Notifications
You must be signed in to change notification settings - Fork 413
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
tusharpandey13
wants to merge
10
commits into
main
Choose a base branch
from
feature/mutateUserSWR
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+800
−117
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
7e648e2
add mutate to user SWR
tusharpandey13 44b91d9
lint
tusharpandey13 197ab5e
Merge branch 'main' into feature/mutateUserSWR
tusharpandey13 6b74969
added exhaustive tests for mutation suport in useUser hook
tusharpandey13 897b00e
Merge branch 'feature/mutateUserSWR' of https://github.com/auth0/next…
tusharpandey13 c55f0aa
added @testing-library/react
tusharpandey13 7c08a9a
added jsdom
tusharpandey13 5f5efc2
make useUser return null user data on error (restored original behavi…
tusharpandey13 f97aeb2
split use-user hook test into unit and integration
tusharpandey13 e6967b5
linting fixes
tusharpandey13 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
|
||
// 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); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 thanrefresh
or so ?