Files
Stirling-PDF/frontend/src/proprietary/routes/AuthCallback.test.tsx
T
James BruntonandGitHub a3e45bc182 Add frontend autoformatting and set CI to require formatted code for all languages (#6052)
# Description of Changes
Changes the strategy for autoformatting to reject PRs if they are not
formatted correctly instead of allowing them to merge and then spawning
a new PR to fix the formatting. The old strategy just caused more work
for us because we'd have to manually approve the followup PR and get it
merged, which required 2 reviewers so in practice it rarely got done and
just meant everyone's PRs ended up containing reformatting for unrelated
files, which makes code review unnecessarily difficult. If the PR's code
is not formatted correctly after this PR, a comment will be added
automatically to tell the author how to run the formatter script to fix
their code so it can go in.

This also enables autoformatting for the frontend code, using Prettier.
I've enabled it for pretty much everything in the frontend folder, other
than 3rd party files and files it doesn't make sense for. I also
excluded Markdown because it sounds likely to be more annoying to have
to autoformat the Markdown in the frontend folder but nowhere else. Open
to changing this though if people disagree.

> [!note]
> 
> Advice to reviewers: The first commit contains all of the actual logic
I've introduced (CI changes, Prettier config, etc.)
> The second commit is just the reformatting of the entire frontend
folder.
> The first commit needs proper review, the second one just give it a
spot-check that it's doing what you'd expect.
2026-04-10 17:41:19 +01:00

174 lines
4.6 KiB
TypeScript

import { describe, it, expect, beforeEach, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import AuthCallback from "@app/routes/AuthCallback";
import { springAuth } from "@app/auth/springAuthClient";
// Mock springAuth
vi.mock("@app/auth/springAuthClient", () => ({
springAuth: {
getSession: vi.fn(),
},
}));
// Mock useNavigate
const mockNavigate = vi.fn();
vi.mock("react-router-dom", async () => {
const actual = await vi.importActual("react-router-dom");
return {
...actual,
useNavigate: () => mockNavigate,
};
});
describe("AuthCallback", () => {
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
// Reset window.location.hash
window.location.hash = "";
});
it("should extract JWT from URL hash and validate it", async () => {
const mockToken = "oauth-jwt-token";
const mockUser = {
id: "123",
email: "[email protected]",
username: "oauthuser",
role: "USER",
};
// Set URL hash with access token
window.location.hash = `#access_token=${mockToken}`;
// Mock successful session validation
vi.mocked(springAuth.getSession).mockResolvedValueOnce({
data: {
session: {
user: mockUser,
access_token: mockToken,
expires_in: 3600,
expires_at: Date.now() + 3600000,
},
},
error: null,
});
const dispatchEventSpy = vi.spyOn(window, "dispatchEvent");
render(
<BrowserRouter>
<AuthCallback />
</BrowserRouter>,
);
await waitFor(() => {
// Verify JWT was stored
expect(localStorage.getItem("stirling_jwt")).toBe(mockToken);
// Verify jwt-available event was dispatched
expect(dispatchEventSpy).toHaveBeenCalledWith(expect.objectContaining({ type: "jwt-available" }));
// Verify getSession was called to validate token
expect(springAuth.getSession).toHaveBeenCalled();
// Verify navigation to home
expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true });
});
});
it("should redirect to login when no access token in hash", async () => {
// No hash or empty hash
window.location.hash = "";
render(
<BrowserRouter>
<AuthCallback />
</BrowserRouter>,
);
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith("/login", {
replace: true,
state: { error: "OAuth login failed - no token received." },
});
expect(localStorage.getItem("stirling_jwt")).toBeNull();
});
});
it("should redirect to login when token validation fails", async () => {
const invalidToken = "invalid-oauth-token";
window.location.hash = `#access_token=${invalidToken}`;
// Mock failed session validation
vi.mocked(springAuth.getSession).mockResolvedValueOnce({
data: { session: null },
error: { message: "Invalid token" },
});
render(
<BrowserRouter>
<AuthCallback />
</BrowserRouter>,
);
await waitFor(() => {
// JWT should be stored initially
expect(localStorage.getItem("stirling_jwt")).toBeNull(); // Cleared after validation failure
// Verify redirect to login
expect(mockNavigate).toHaveBeenCalledWith("/login", {
replace: true,
state: { error: "OAuth login failed - invalid token." },
});
});
});
it("should handle errors gracefully", async () => {
const mockToken = "error-token";
window.location.hash = `#access_token=${mockToken}`;
// Mock getSession throwing error
vi.mocked(springAuth.getSession).mockRejectedValueOnce(new Error("Network error"));
render(
<BrowserRouter>
<AuthCallback />
</BrowserRouter>,
);
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith("/login", {
replace: true,
state: { error: "OAuth login failed. Please try again." },
});
});
});
it("should display loading state while processing", () => {
window.location.hash = "#access_token=processing-token";
vi.mocked(springAuth.getSession).mockImplementationOnce(
() =>
new Promise((resolve) =>
setTimeout(
() =>
resolve({
data: { session: null },
error: { message: "Token expired" },
}),
100,
),
),
);
const { getByText } = render(
<BrowserRouter>
<AuthCallback />
</BrowserRouter>,
);
expect(getByText("Completing authentication")).toBeInTheDocument();
});
});