Files
jobtrackingapp/job-tracker-ui/src/LandingPage.authRedirect.test.tsx
T
2026-08-29 22:30:08 +02:00

51 lines
1.9 KiB
TypeScript

import React from "react";
import "@testing-library/jest-dom";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
import { api } from "./api";
import LandingPage from "./views/LandingPage";
import { I18nProvider } from "./i18n/I18nProvider";
jest.mock("./api", () => ({
api: {
get: jest.fn(),
post: jest.fn(),
interceptors: { request: { use: jest.fn() }, response: { use: jest.fn() } },
},
}));
const mockedApi = api as jest.Mocked<typeof api>;
function LoginStub() {
const location = useLocation() as { state?: { from?: string } };
return <div>login page, from={location.state?.from ?? "none"}</div>;
}
// Regression check for the auth-guard fix: a protected route bounces an
// unauthenticated visitor to "/" with `state.from` set to the page they
// wanted. The home page must forward that state to /login so sign-in
// returns them to the originally-requested page instead of dropping them
// on /jobs.
describe("LandingPage forwards deep-link intent to /login", () => {
it("preserves location.state.from through the Sign in CTA", async () => {
mockedApi.get.mockRejectedValueOnce(new Error("401")); // /auth/me: not signed in
render(
<MemoryRouter initialEntries={[{ pathname: "/", state: { from: "/jobs/42" } }]}>
<Routes>
<Route path="/" element={<I18nProvider><LandingPage /></I18nProvider>} />
<Route path="/login" element={<LoginStub />} />
</Routes>
</MemoryRouter>,
);
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith("/auth/me"));
const signInButtons = await screen.findAllByText("Sign in", { selector: "button" });
await userEvent.click(signInButtons[0]);
expect(await screen.findByText("login page, from=/jobs/42")).toBeInTheDocument();
});
});