-
-
Notifications
You must be signed in to change notification settings - Fork 46
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Miłosz <[email protected]>
- Loading branch information
1 parent
d23bb7c
commit 06d876f
Showing
9 changed files
with
317 additions
and
2 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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 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 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 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 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,4 @@ | ||
// Copyright © 2024 Ory Corp | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
export { useSession } from "./useSession" |
This file contains 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,162 @@ | ||
// Copyright © 2024 Ory Corp | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
// useSession.test.tsx | ||
|
||
import { Session } from "@ory/client-fetch" | ||
import "@testing-library/jest-dom" | ||
import "@testing-library/jest-dom/jest-globals" | ||
import { act, render, screen, waitFor } from "@testing-library/react" | ||
import { useOryFlow } from "../context/flow-context" | ||
import { frontendClient } from "../util/client" | ||
import { sessionStore, useSession } from "./useSession" | ||
|
||
// Mock the necessary imports | ||
jest.mock("../context/flow-context", () => ({ | ||
useOryFlow: jest.fn(), | ||
})) | ||
|
||
jest.mock("../util/client", () => ({ | ||
frontendClient: jest.fn(() => ({ | ||
toSession: jest.fn(), | ||
})), | ||
})) | ||
|
||
// Create a test component to use the hook | ||
const TestComponent = () => { | ||
const { session, isLoading, error } = useSession() | ||
|
||
if (isLoading) return <div>Loading...</div> | ||
if (error) return <div>Error: {error}</div> | ||
if (session) return <div>Session: {session.id}</div> | ||
|
||
return <div>No session</div> | ||
} | ||
|
||
describe("useSession", () => { | ||
const mockSession: Session = { | ||
id: "test-session-id", | ||
identity: { | ||
id: "test-identity-id", | ||
traits: {}, | ||
schema_id: "", | ||
schema_url: "", | ||
}, | ||
expires_at: new Date(), | ||
} | ||
const mockConfig = { | ||
sdk: { url: "https://mock-sdk-url" }, | ||
} | ||
|
||
beforeEach(() => { | ||
jest.clearAllMocks() | ||
// Mock the flow context | ||
;(useOryFlow as jest.Mock).mockReturnValue({ config: mockConfig }) | ||
sessionStore.setState({ | ||
isLoading: false, | ||
session: undefined, | ||
error: undefined, | ||
}) | ||
}) | ||
|
||
it("fetches and sets session successfully", async () => { | ||
;(frontendClient as jest.Mock).mockReturnValue({ | ||
toSession: jest.fn().mockResolvedValue(mockSession), | ||
}) | ||
|
||
render(<TestComponent />) | ||
|
||
// Initially, it should show loading | ||
expect(screen.getByText("Loading...")).toBeInTheDocument() | ||
|
||
// Wait for the hook to update | ||
await waitFor(() => | ||
expect( | ||
screen.getByText(`Session: ${mockSession.id}`), | ||
).toBeInTheDocument(), | ||
) | ||
|
||
// Verify that the session data is displayed | ||
expect(screen.getByText(`Session: ${mockSession.id}`)).toBeInTheDocument() | ||
}) | ||
|
||
it("doesn't refetch session if a session is set", async () => { | ||
;(frontendClient as jest.Mock).mockReturnValue({ | ||
toSession: jest.fn().mockResolvedValue(mockSession), | ||
}) | ||
|
||
render(<TestComponent />) | ||
|
||
// Initially, it should show loading | ||
expect(screen.getByText("Loading...")).toBeInTheDocument() | ||
|
||
// Wait for the hook to update | ||
await waitFor(() => | ||
expect( | ||
screen.getByText(`Session: ${mockSession.id}`), | ||
).toBeInTheDocument(), | ||
) | ||
|
||
// Verify that the session data is displayed | ||
expect(screen.getByText(`Session: ${mockSession.id}`)).toBeInTheDocument() | ||
|
||
// this is fine, because jest is not calling the function | ||
// eslint-disable-next-line @typescript-eslint/unbound-method | ||
expect(frontendClient(mockConfig.sdk.url).toSession).toHaveBeenCalledTimes( | ||
1, | ||
) | ||
|
||
act(() => { | ||
render(<TestComponent />) | ||
}) | ||
|
||
// this is fine, because jest is not calling the function | ||
// eslint-disable-next-line @typescript-eslint/unbound-method | ||
expect(frontendClient(mockConfig.sdk.url).toSession).toHaveBeenCalledTimes( | ||
1, | ||
) | ||
}) | ||
|
||
it("handles errors during session fetching", async () => { | ||
const errorMessage = "Failed to fetch session" | ||
;(frontendClient as jest.Mock).mockReturnValue({ | ||
toSession: jest.fn().mockRejectedValue(new Error(errorMessage)), | ||
}) | ||
|
||
render(<TestComponent />) | ||
|
||
// Initially, it should show loading | ||
expect(screen.getByText("Loading...")).toBeInTheDocument() | ||
|
||
// Wait for the hook to update after the error | ||
await waitFor(() => | ||
expect(screen.getByText(`Error: ${errorMessage}`)).toBeInTheDocument(), | ||
) | ||
|
||
// Verify that the error message is displayed | ||
expect(screen.getByText(`Error: ${errorMessage}`)).toBeInTheDocument() | ||
}) | ||
|
||
it("does not fetch session if already loading or session is set", async () => { | ||
;(frontendClient as jest.Mock).mockReturnValue({ | ||
toSession: jest.fn(), | ||
}) | ||
|
||
// First render: no session, simulate loading | ||
render(<TestComponent />) | ||
|
||
// Initially, it should show loading | ||
expect(screen.getByText("Loading...")).toBeInTheDocument() | ||
|
||
// Simulate session already being set in the store | ||
await waitFor(() => | ||
expect(screen.getByText("No session")).toBeInTheDocument(), | ||
) | ||
|
||
// this is fine, because jest is not calling the function | ||
// eslint-disable-next-line @typescript-eslint/unbound-method | ||
expect(frontendClient(mockConfig.sdk.url).toSession).toHaveBeenCalledTimes( | ||
1, | ||
) | ||
}) | ||
}) |
This file contains 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,74 @@ | ||
// Copyright © 2024 Ory Corp | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
import { Session } from "@ory/client-fetch" | ||
import { useCallback, useEffect } from "react" | ||
import { create, useStore } from "zustand" | ||
import { subscribeWithSelector } from "zustand/middleware" | ||
import { useOryFlow } from "../context/flow-context" | ||
import { frontendClient } from "../util/client" | ||
|
||
type SessionStore = { | ||
setIsLoading: (loading: boolean) => void | ||
setSession: (session: Session) => void | ||
isLoading: boolean | ||
session: Session | undefined | ||
error: string | undefined | ||
setError: (error: string | undefined) => void | ||
} | ||
|
||
export const sessionStore = create<SessionStore>()( | ||
subscribeWithSelector((set) => ({ | ||
isLoading: false, | ||
setIsLoading: (isLoading: boolean) => set({ isLoading }), | ||
session: undefined, | ||
setSession: (session: Session) => set({ session }), | ||
error: undefined, | ||
setError: (error: string | undefined) => set({ error }), | ||
})), | ||
) | ||
|
||
/** | ||
* A hook to get the current session from the Ory Network. | ||
* | ||
* Usage: | ||
* ```ts | ||
* const { session, error, isLoading } = useSession() | ||
* ``` | ||
* | ||
* @returns The current session, error and loading state. | ||
*/ | ||
export const useSession = () => { | ||
const { config } = useOryFlow() | ||
const store = useStore(sessionStore) | ||
|
||
const fetchSession = useCallback(async () => { | ||
const { session, isLoading, setSession, setIsLoading, setError } = | ||
sessionStore.getState() | ||
|
||
if (!!session || isLoading) { | ||
return | ||
} | ||
|
||
setIsLoading(true) | ||
|
||
try { | ||
const sessionData = await frontendClient(config.sdk.url).toSession() | ||
setSession(sessionData) | ||
} catch (e) { | ||
setError(e instanceof Error ? e.message : "Unknown error occurred") | ||
} finally { | ||
setIsLoading(false) | ||
} | ||
}, [config.sdk.url]) | ||
|
||
useEffect(() => { | ||
void fetchSession() | ||
}, [fetchSession]) | ||
|
||
return { | ||
session: store.session, | ||
error: store.error, | ||
isLoading: store.isLoading, | ||
} | ||
} |
This file contains 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