v4: /follow/playlists opens the followed playlists' feed, and a page's test opens it through the app's routes — the path was a 404 since the two views of the followed feed became pages: the route table held each feed tab as an exact path, /follow, so /follow/playlists fell to /:handle/*, which read "follow" as a category and "playlists" as a tab it hasn't. /music/follow/playlists, which goes through that route, worked. The tabs' routes now take what follows them (/${tab}/*), which Feed already reads and refuses when it names no view.
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 57s
Build and Deploy Static Documentation Site / build-and-push (push) Successful in 28s

No test saw it because each page's test mounted the page on a route pattern of its own, a copy of App's, with stand-in pages where a redirect lands: Index's parsed the path itself, and passed on one the app doesn't serve. renderPage (src/test/render.tsx) now opens a URL through AppRoutes, which App.tsx exports for it, inside the real providers, and every page's test uses it: the page is the one the app routes that URL to, behind its guard, and a redirect is checked by the path it lands on. An entry may be a location, to arrive with the state a link hands over. Every page being loaded with its route, the first query after opening one waits. src/test/App.test.tsx tests the table itself: the paths that are a feed, those that are not found, those that send a guest to sign in and back, and those that send a signed-in user home.

The profile's test held /@ann/dumps/x to be a path the profile answers as not found, which only its own pattern made true: in the app it is a dump's page. It now asks for /@ann/dumps/x/y. The tests of the two guards still mount them around a stand-in child, being tests of the guard alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-10 19:59:52 +00:00
parent cbb770bff8
commit 3e15e9a4f2
20 changed files with 263 additions and 290 deletions

View File

@@ -203,15 +203,22 @@ function HandleRoutes() {
: <Feed categorySlug={handle} />; : <Feed categorySlug={handle} />;
} }
/** Renders the route table, and the floating buttons over every page. */ /**
function AppRoutes() { * Renders the route table, and the floating buttons over every page. Exported
* for the tests, which reach a page through it as a visit does.
*/
export function AppRoutes(): React.JSX.Element {
return ( return (
<> <>
<Suspense> <Suspense>
<Routes> <Routes>
<Route path="/" element={<Feed />} /> <Route path="/" element={<Feed />} />
{
/* The splat takes the `follow` tab's view, which `Feed` reads from
the path; without it `/follow/playlists` is category `follow`. */
}
{FEED_TABS.map((tab) => ( {FEED_TABS.map((tab) => (
<Route key={tab} path={`/${tab}`} element={<Feed />} /> <Route key={tab} path={`/${tab}/*`} element={<Feed />} />
))} ))}
<Route path="/search" element={<Search />} /> <Route path="/search" element={<Search />} />
<Route path="/search/:searchTab" element={<Search />} /> <Route path="/search/:searchTab" element={<Search />} />

74
src/test/App.test.tsx Normal file
View File

@@ -0,0 +1,74 @@
import { describe, expect, test } from "vitest";
import { screen, waitFor } from "@testing-library/react";
import { route } from "./fetch.ts";
import { makeCategory, makeSession, page } from "./fixtures.ts";
import { currentPath, renderPage } from "./render.tsx";
const music = makeCategory({ id: "c-music", slug: "music", name: "Music" });
const next = (path: string) => `/login?next=${encodeURIComponent(path)}`;
function open(url: string, session: ReturnType<typeof makeSession> | null) {
route("GET /api/dumps", () => page([]));
renderPage(url, { session, categories: [music] });
}
describe("App's routes", () => {
test.each([
"/",
"/hot",
"/new",
"/journal",
"/follow",
"/follow/playlists",
"/music",
"/music/new",
"/music/follow",
"/music/follow/playlists",
])("%s is a feed", async (url) => {
open(url, makeSession());
// The tab bar, which the feed draws at two widths.
expect(await screen.findAllByRole("button", { name: "Followed" })).not
.toHaveLength(0);
expect(currentPath()).toBe(url);
expect(screen.queryByRole("heading", { name: "404" })).toBeNull();
});
test.each([
"/hot/more",
"/follow/users",
"/follow/nope",
"/follow/playlists/more",
"/nope",
"/music/nope",
"/music/hot/more",
"/music/follow/users",
"/search/users/more",
])("%s is not found", async (url) => {
open(url, makeSession());
expect(await screen.findByRole("heading", { name: "404" }))
.toBeInTheDocument();
});
test.each([
"/follow",
"/follow/playlists",
"/music/follow/playlists",
"/notifications",
"/settings",
"/manage",
"/community",
"/community/monthly",
"/@ann/dumps/a-find/edit",
])("%s sends a guest to sign in, and back", async (url) => {
open(url, null);
await waitFor(() => expect(currentPath()).toBe(next(url)));
});
test.each(["/login", "/register"])(
"%s sends a signed-in user home",
async (url) => {
open(url, makeSession());
await waitFor(() => expect(currentPath()).toBe("/"));
},
);
});

View File

@@ -1,11 +1,9 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { screen, waitFor } from "@testing-library/react"; import { screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Route } from "react-router";
import { Authorize } from "../../pages/Authorize.tsx";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { makeSession } from "../fixtures.ts"; import { makeSession } from "../fixtures.ts";
import { currentPath, renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
const QUERY = const QUERY =
"?response_type=code&client_id=https%3A%2F%2Fmusic.example&redirect_uri=https%3A%2F%2Fmusic.example%2Ffederation%2Fcallback&state=s1&code_challenge=c1&code_challenge_method=S256&nonce=n1"; "?response_type=code&client_id=https%3A%2F%2Fmusic.example&redirect_uri=https%3A%2F%2Fmusic.example%2Ffederation%2Fcallback&state=s1&code_challenge=c1&code_challenge_method=S256&nonce=n1";
@@ -24,12 +22,7 @@ describe("Authorize", () => {
function open(session = ann) { function open(session = ann) {
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<Authorize />, { renderPage(`/authorize${QUERY}`, { session });
route: `/authorize${QUERY}`,
path: "/authorize",
session,
extraRoutes: <Route path="/login" element={<p>login page</p>} />,
});
return user; return user;
} }
@@ -78,12 +71,8 @@ describe("Authorize", () => {
}); });
test("a signed-out visitor logs in first and comes back", async () => { test("a signed-out visitor logs in first and comes back", async () => {
renderApp(<Authorize />, { renderPage(`/authorize${QUERY}`);
route: `/authorize${QUERY}`, await screen.findByRole("heading", { name: "Log in" });
path: "/authorize",
extraRoutes: <Route path="/login" element={<p>login page</p>} />,
});
await screen.findByText("login page");
expect(currentPath()).toBe( expect(currentPath()).toBe(
`/login?next=${encodeURIComponent(`/authorize${QUERY}`)}`, `/login?next=${encodeURIComponent(`/authorize${QUERY}`)}`,
); );

View File

@@ -1,7 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { screen } from "@testing-library/react"; import { screen } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Community } from "../../pages/Community.tsx";
import { calls, route } from "../fetch.ts"; import { calls, route } from "../fetch.ts";
import { import {
makeDump, makeDump,
@@ -10,7 +9,7 @@ import {
makeUser, makeUser,
wire, wire,
} from "../fixtures.ts"; } from "../fixtures.ts";
import { currentPath, renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
function stats( function stats(
{ {
@@ -35,7 +34,7 @@ function stats(
function open(url: string) { function open(url: string) {
const user = userEvent.setup(); const user = userEvent.setup();
const session = makeSession({ username: "ann" }); const session = makeSession({ username: "ann" });
renderApp(<Community />, { route: url, path: "/community/*", session }); renderPage(url, { session });
return user; return user;
} }

View File

@@ -1,10 +1,6 @@
import { describe, expect, test, vi } from "vitest"; import { describe, expect, test, vi } from "vitest";
import { act, screen, waitFor, within } from "@testing-library/react"; import { act, screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Link, Route } from "react-router";
import { Dump } from "../../pages/Dump.tsx";
import { DumpEdit } from "../../pages/DumpEdit.tsx";
import { RestrictedLoggedIn } from "../../pages/RestrictedLoggedIn.tsx";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { import {
makeCategory, makeCategory,
@@ -15,7 +11,7 @@ import {
makeUser, makeUser,
wire, wire,
} from "../fixtures.ts"; } from "../fixtures.ts";
import { currentPath, renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts"; import { FakeWebSocket } from "../ws.ts";
const owner = makeSession({ id: "owner", username: "owner" }); const owner = makeSession({ id: "owner", username: "owner" });
@@ -48,15 +44,7 @@ function openDump(
url = "/@owner/dumps/a-find", url = "/@owner/dumps/a-find",
) { ) {
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<Dump />, { renderPage(url, { session, categories: [music] });
route: url,
path: "/:handle/dumps/:slug",
session,
categories: [music],
extraRoutes: (
<Route path="/:handle/dumps/:slug/edit" element={<p>edit page</p>} />
),
});
const socket = FakeWebSocket.last; const socket = FakeWebSocket.last;
socket.welcome(); socket.welcome();
return { user, socket }; return { user, socket };
@@ -160,7 +148,9 @@ describe("Dump page", () => {
dumpRoutes(); dumpRoutes();
const { user } = openDump(owner); const { user } = openDump(owner);
await user.click(await screen.findByRole("link", { name: "Edit" })); await user.click(await screen.findByRole("link", { name: "Edit" }));
expect(currentPath()).toBe("/@owner/dumps/a-find/edit"); await waitFor(() =>
expect(currentPath()).toBe("/@owner/dumps/a-find/edit")
);
}); });
test("the title can be edited from the keyboard", async () => { test("the title can be edited from the keyboard", async () => {
@@ -268,20 +258,9 @@ describe("Dump page", () => {
({ params }) => wire([params.id === first.id ? second : first]), ({ params }) => wire([params.id === first.id ? second : first]),
); );
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<Dump />, { // Arrived from a card, which hands its dump over with the link.
route: "/start", renderPage({ pathname: "/@owner/dumps/a-find", state: { dump: first } });
path: "/:handle/dumps/:slug",
extraRoutes: (
<Route
path="/start"
element={
<Link to="/@owner/dumps/a-find" state={{ dump: first }}>open</Link>
}
/>
),
});
FakeWebSocket.last.welcome(); FakeWebSocket.last.welcome();
await user.click(screen.getByRole("link", { name: "open" }));
await user.click(await screen.findByRole("link", { name: "Next find" })); await user.click(await screen.findByRole("link", { name: "Next find" }));
await user.click(await screen.findByRole("link", { name: "A find" })); await user.click(await screen.findByRole("link", { name: "A find" }));
expect(await screen.findByRole("heading", { name: "A find", level: 1 })) expect(await screen.findByRole("heading", { name: "A find", level: 1 }))
@@ -455,27 +434,18 @@ describe("DumpEdit page", () => {
function openEdit(dump: ReturnType<typeof makeDump>, session = owner) { function openEdit(dump: ReturnType<typeof makeDump>, session = owner) {
route("GET /api/users/:u/dumps/:slug", () => wire(dump)); route("GET /api/users/:u/dumps/:slug", () => wire(dump));
const user = userEvent.setup(); const user = userEvent.setup();
renderApp( renderPage(`/@owner/dumps/${dump.slug}/edit`, {
<RestrictedLoggedIn> session,
<DumpEdit /> categories: [music],
</RestrictedLoggedIn>, });
{
route: `/@owner/dumps/${dump.slug}/edit`,
path: "/:handle/dumps/:slug/edit",
session,
categories: [music],
extraRoutes: (
<>
<Route path="/:handle/dumps/:slug" element={<p>dump page</p>} />
<Route path="/" element={<p>home</p>} />
</>
),
},
);
FakeWebSocket.last.welcome(); FakeWebSocket.last.welcome();
return user; return user;
} }
/** Waits for the editor to have handed over to a dump's page. */
const onDumpPage = () =>
waitFor(() => expect(currentPath()).toMatch(/^\/@[^/]+\/dumps\/[^/]+$/));
const urlDump = () => const urlDump = () =>
makeDump({ makeDump({
id: "d1", id: "d1",
@@ -515,7 +485,7 @@ describe("DumpEdit page", () => {
await user.click(screen.getByRole("button", { name: "Music" })); await user.click(screen.getByRole("button", { name: "Music" }));
await user.click(screen.getByRole("button", { name: "Private" })); await user.click(screen.getByRole("button", { name: "Private" }));
await user.click(screen.getByRole("button", { name: "Save" })); await user.click(screen.getByRole("button", { name: "Save" }));
await screen.findByText("dump page"); await onDumpPage();
expect(currentPath()).toBe("/@owner/dumps/new-title"); expect(currentPath()).toBe("/@owner/dumps/new-title");
expect(calls("PUT /api/dumps/:id")[0].body).toEqual({ expect(calls("PUT /api/dumps/:id")[0].body).toEqual({
url: "https://a.test/", url: "https://a.test/",
@@ -542,7 +512,7 @@ describe("DumpEdit page", () => {
await user.type(title, "A Find!"); await user.type(title, "A Find!");
expect(link).toHaveValue("a-find"); expect(link).toHaveValue("a-find");
await user.click(screen.getByRole("button", { name: "Save" })); await user.click(screen.getByRole("button", { name: "Save" }));
await screen.findByText("dump page"); await onDumpPage();
expect(calls("PUT /api/dumps/:id")[0].body).not.toHaveProperty("slug"); expect(calls("PUT /api/dumps/:id")[0].body).not.toHaveProperty("slug");
}); });
@@ -572,7 +542,7 @@ describe("DumpEdit page", () => {
const user = openEdit(urlDump()); const user = openEdit(urlDump());
await user.clear(await screen.findByLabelText("Why?")); await user.clear(await screen.findByLabelText("Why?"));
await user.click(screen.getByRole("button", { name: "Save" })); await user.click(screen.getByRole("button", { name: "Save" }));
await screen.findByText("dump page"); await onDumpPage();
expect(calls("PUT /api/dumps/:id")[0].body).toHaveProperty("comment", null); expect(calls("PUT /api/dumps/:id")[0].body).toHaveProperty("comment", null);
}); });
@@ -642,7 +612,7 @@ describe("DumpEdit page", () => {
); );
await user.click(screen.getByRole("button", { name: "Private" })); await user.click(screen.getByRole("button", { name: "Private" }));
await user.click(screen.getByRole("button", { name: "Save" })); await user.click(screen.getByRole("button", { name: "Save" }));
await screen.findByText("dump page"); await onDumpPage();
const [put] = calls("PUT /api/dumps/:id/file"); const [put] = calls("PUT /api/dumps/:id/file");
const form = put.body as FormData; const form = put.body as FormData;
expect(form.get("file")).toBeInstanceOf(File); expect(form.get("file")).toBeInstanceOf(File);
@@ -676,7 +646,7 @@ describe("DumpEdit page", () => {
await user.click(screen.getByRole("button", { name: "Save" })); await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("File too large (max 50 MB)")) expect(await screen.findByText("File too large (max 50 MB)"))
.toBeInTheDocument(); .toBeInTheDocument();
expect(screen.queryByText("dump page")).not.toBeInTheDocument(); expect(currentPath()).toBe(`/@owner/dumps/${fileDump.slug}/edit`);
expect(calls("PUT /api/dumps/:id/file")).toHaveLength(1); expect(calls("PUT /api/dumps/:id/file")).toHaveLength(1);
expect(calls("PUT /api/dumps/:id")).toHaveLength(0); expect(calls("PUT /api/dumps/:id")).toHaveLength(0);
}); });
@@ -719,7 +689,7 @@ describe("DumpEdit page", () => {
name: "Delete dump", name: "Delete dump",
}), }),
); );
await screen.findByText("home"); await waitFor(() => expect(currentPath()).toBe("/"));
expect( expect(
JSON.parse( JSON.parse(
document.querySelector('[data-testid="location"]')!.getAttribute( document.querySelector('[data-testid="location"]')!.getAttribute(
@@ -760,17 +730,12 @@ describe("DumpEdit page", () => {
expect(await screen.findByText("Not an image")).toBeInTheDocument(); expect(await screen.findByText("Not an image")).toBeInTheDocument();
}); });
test("guests are sent to log in", () => { test("guests are sent to log in, and back", async () => {
renderApp( renderPage("/@owner/dumps/x/edit");
<RestrictedLoggedIn> await waitFor(() =>
<DumpEdit /> expect(currentPath()).toBe(
</RestrictedLoggedIn>, `/login?next=${encodeURIComponent("/@owner/dumps/x/edit")}`,
{ )
route: "/@owner/dumps/x/edit",
path: "/:handle/dumps/:slug/edit",
extraRoutes: <Route path="/login" element={<p>login page</p>} />,
},
); );
expect(screen.getByText("login page")).toBeInTheDocument();
}); });
}); });

View File

@@ -1,20 +1,14 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { screen } from "@testing-library/react"; import { screen, waitFor } from "@testing-library/react";
import { Route } from "react-router";
import { FederationCallback } from "../../pages/FederationCallback.tsx";
import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts"; import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { makeSession, wire } from "../fixtures.ts"; import { makeSession, page, wire } from "../fixtures.ts";
import { renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
/** Opens the callback, in a tab that started the sign-in of state `s`. */ /** Opens the callback, in a tab that started the sign-in of state `s`. */
function open(query: string, started = "s") { function open(query: string, started = "s") {
sessionStorage.setItem("federationState", started); sessionStorage.setItem("federationState", started);
renderApp(<FederationCallback />, { renderPage(`/federation/callback${query}`);
route: `/federation/callback${query}`,
path: "/federation/callback",
extraRoutes: <Route path="/" element={<p>home page</p>} />,
});
} }
describe("FederationCallback", () => { describe("FederationCallback", () => {
@@ -23,8 +17,9 @@ describe("FederationCallback", () => {
"POST /api/federation/sessions", "POST /api/federation/sessions",
() => wire(makeSession({ username: "alice@home.example" })), () => wire(makeSession({ username: "alice@home.example" })),
); );
route("GET /api/dumps", () => page([]));
open("?code=c&state=s&iss=https%3A%2F%2Fhome.example"); open("?code=c&state=s&iss=https%3A%2F%2Fhome.example");
await screen.findByText("home page"); await waitFor(() => expect(currentPath()).toBe("/"));
expect(calls("POST /api/federation/sessions").map((c) => c.body)).toEqual( expect(calls("POST /api/federation/sessions").map((c) => c.body)).toEqual(
[{ code: "c", state: "s" }], [{ code: "c", state: "s" }],
); );

View File

@@ -1,13 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { act, screen, waitFor, within } from "@testing-library/react"; import { act, screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { useLocation } from "react-router";
import { Index } from "../../pages/Index.tsx";
import {
FEED_TABS,
type FeedTab,
type FollowView,
} from "../../../shared/paths.ts";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { import {
makeCategory, makeCategory,
@@ -16,41 +9,19 @@ import {
page, page,
wire, wire,
} from "../fixtures.ts"; } from "../fixtures.ts";
import { currentPath, renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts"; import { FakeWebSocket } from "../ws.ts";
import { FakeIntersectionObserver } from "../setup.ts"; import { FakeIntersectionObserver } from "../setup.ts";
const HOUR = 3_600_000; const HOUR = 3_600_000;
const music = makeCategory({ id: "c-music", slug: "music", name: "Music" }); const music = makeCategory({ id: "c-music", slug: "music", name: "Music" });
/** Reads a feed's path as `App`'s routes do. */
function Scoped() {
const { pathname } = useLocation();
const segments = pathname.split("/").filter(Boolean);
const isTab = (FEED_TABS as readonly string[]).includes(segments[0] ?? "");
const categorySlug = isTab ? undefined : segments[0];
const [feedTab, followView] = segments.slice(isTab ? 0 : 1);
return (
<Index
key={categorySlug ?? ""}
categorySlug={categorySlug}
feedTab={feedTab as FeedTab | undefined}
followView={followView as FollowView | undefined}
/>
);
}
function setup( function setup(
url: string, url: string,
{ session = null as ReturnType<typeof makeSession> | null } = {}, { session = null as ReturnType<typeof makeSession> | null } = {},
) { ) {
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<Scoped />, { renderPage(url, { session, categories: [music] });
route: url,
path: "*",
session,
categories: [music],
});
const socket = FakeWebSocket.last; const socket = FakeWebSocket.last;
socket.welcome(); socket.welcome();
return { user, socket }; return { user, socket };
@@ -309,10 +280,12 @@ describe("Index feeds", () => {
.toBeInTheDocument(); .toBeInTheDocument();
}); });
test("a guest on the follow tab is sent to sign in, and back", () => { test("a guest on the follow tab is sent to sign in, and back", async () => {
route("GET /api/dumps", () => page([older])); route("GET /api/dumps", () => page([older]));
setup("/music/follow"); setup("/music/follow");
expect(currentPath()).toBe("/login?next=%2Fmusic%2Ffollow"); await waitFor(() =>
expect(currentPath()).toBe("/login?next=%2Fmusic%2Ffollow")
);
}); });
test("the Android share sheet opens the new-dump form with the link", async () => { test("the Android share sheet opens the new-dump form with the link", async () => {

View File

@@ -1,10 +1,9 @@
import { afterEach, describe, expect, test, vi } from "vitest"; import { afterEach, describe, expect, test, vi } from "vitest";
import { screen, waitFor, within } from "@testing-library/react"; import { screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Manage } from "../../pages/Manage.tsx";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { makeCategory, makeSession, wire } from "../fixtures.ts"; import { makeCategory, makeSession, wire } from "../fixtures.ts";
import { renderApp } from "../render.tsx"; import { renderPage } from "../render.tsx";
const instance = vi.hoisted(() => ({ const instance = vi.hoisted(() => ({
federationIncoming: true, federationIncoming: true,
@@ -31,7 +30,7 @@ async function group(label: string) {
function open(session = admin) { function open(session = admin) {
route("GET /api/federation/peers", () => [], { fallback: true }); route("GET /api/federation/peers", () => [], { fallback: true });
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<Manage />, { route: "/manage", path: "/manage", session }); renderPage("/manage", { session });
return user; return user;
} }

View File

@@ -1,12 +1,12 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { screen, waitFor } from "@testing-library/react"; import { screen, waitFor } from "@testing-library/react";
import { NotFound } from "../../pages/NotFound.tsx"; import { renderPage } from "../render.tsx";
import { renderWithContexts } from "../render.tsx";
describe("NotFound", () => { describe("NotFound", () => {
test("NotFound", async () => { test("a path the app has no page for", async () => {
renderWithContexts(<NotFound />, { route: "/nope" }); renderPage("/search/users/more");
expect(screen.getByRole("heading", { name: "404" })).toBeInTheDocument(); expect(await screen.findByRole("heading", { name: "404" }))
.toBeInTheDocument();
await waitFor(() => expect(document.title).toMatch(/^Page not found/)); await waitFor(() => expect(document.title).toMatch(/^Page not found/));
expect(screen.getByRole("link", { name: "Go home" })).toHaveAttribute( expect(screen.getByRole("link", { name: "Go home" })).toHaveAttribute(
"href", "href",

View File

@@ -1,11 +1,10 @@
import { describe, expect, test, vi } from "vitest"; import { describe, expect, test, vi } from "vitest";
import { act, screen, waitFor } from "@testing-library/react"; import { act, screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Notifications } from "../../pages/Notifications.tsx";
import type { Notification } from "../../../shared/notification.ts"; import type { Notification } from "../../../shared/notification.ts";
import { calls, deferred, fail, route } from "../fetch.ts"; import { calls, deferred, fail, route } from "../fetch.ts";
import { makeNotification, makeSession, page, wire } from "../fixtures.ts"; import { makeNotification, makeSession, page, wire } from "../fixtures.ts";
import { renderApp } from "../render.tsx"; import { renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts"; import { FakeWebSocket } from "../ws.ts";
import { FakeIntersectionObserver } from "../setup.ts"; import { FakeIntersectionObserver } from "../setup.ts";
@@ -22,10 +21,7 @@ function open(items: Notification[], { hasMore = false } = {}) {
); );
route("POST /api/me/notifications/read", () => ({})); route("POST /api/me/notifications/read", () => ({}));
const user = userEvent.setup(); const user = userEvent.setup();
const view = renderApp(<Notifications />, { const view = renderPage("/notifications", { session: me });
session: me,
route: "/notifications",
});
const socket = FakeWebSocket.last; const socket = FakeWebSocket.last;
socket.welcome({ socket.welcome({
unreadNotificationCount: items.filter((n) => !n.read).length, unreadNotificationCount: items.filter((n) => !n.read).length,
@@ -247,7 +243,7 @@ describe("Notifications", () => {
test("a failed load shows the server's reason", async () => { test("a failed load shows the server's reason", async () => {
route("GET /api/me/notifications", () => fail("Database is locked", 500)); route("GET /api/me/notifications", () => fail("Database is locked", 500));
renderApp(<Notifications />, { session: me }); renderPage("/notifications", { session: me });
const alert = await screen.findByRole("alert"); const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent("Failed to load"); expect(alert).toHaveTextContent("Failed to load");
expect(alert).toHaveTextContent("Database is locked"); expect(alert).toHaveTextContent("Database is locked");
@@ -303,7 +299,7 @@ describe("Notifications", () => {
const list = deferred<unknown>(); const list = deferred<unknown>();
route("GET /api/me/notifications", () => list.promise); route("GET /api/me/notifications", () => list.promise);
route("POST /api/me/notifications/read", () => ({})); route("POST /api/me/notifications/read", () => ({}));
renderApp(<Notifications />, { session: me, route: "/notifications" }); renderPage("/notifications", { session: me });
const socket = FakeWebSocket.last; const socket = FakeWebSocket.last;
socket.welcome({ unreadNotificationCount: 1 }); socket.welcome({ unreadNotificationCount: 1 });
await waitFor(() => await waitFor(() =>
@@ -343,7 +339,7 @@ describe("Notifications", () => {
: page([n.upvoted], false), : page([n.upvoted], false),
); );
route("POST /api/me/notifications/read", () => ({})); route("POST /api/me/notifications/read", () => ({}));
renderApp(<Notifications />, { session: me }); renderPage("/notifications", { session: me });
await screen.findByText(/started following you/); await screen.findByText(/started following you/);
act(() => FakeIntersectionObserver.instances.at(-1)!.report(true)); act(() => FakeIntersectionObserver.instances.at(-1)!.report(true));
expect(await screen.findByText(/^upvoted$/)).toBeInTheDocument(); expect(await screen.findByText(/^upvoted$/)).toBeInTheDocument();

View File

@@ -7,8 +7,6 @@ import {
within, within,
} from "@testing-library/react"; } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Route } from "react-router";
import { PlaylistDetail } from "../../pages/PlaylistDetail.tsx";
import type { Dump } from "../../../shared/dump.ts"; import type { Dump } from "../../../shared/dump.ts";
import type { Playlist } from "../../../shared/playlist.ts"; import type { Playlist } from "../../../shared/playlist.ts";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
@@ -19,7 +17,7 @@ import {
makeSession, makeSession,
wire, wire,
} from "../fixtures.ts"; } from "../fixtures.ts";
import { currentPath, renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts"; import { FakeWebSocket } from "../ws.ts";
const owner = makeSession({ id: "owner", username: "owner" }); const owner = makeSession({ id: "owner", username: "owner" });
@@ -54,21 +52,7 @@ function open(
() => wire({ ...pl, dumps: items }), () => wire({ ...pl, dumps: items }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<PlaylistDetail />, { renderPage(url, { session, categories });
route: url,
path: "/:handle/playlists/:slug",
session,
categories,
extraRoutes: (
<>
<Route path="/" element={<p>home</p>} />
<Route
path="/:handle/playlists/:slug/edit"
element={<PlaylistDetail editing />}
/>
</>
),
});
const socket = FakeWebSocket.last; const socket = FakeWebSocket.last;
socket.welcome(); socket.welcome();
return { user, socket, pl }; return { user, socket, pl };
@@ -103,10 +87,7 @@ describe("PlaylistDetail", () => {
"GET /api/users/:u/playlists/:slug", "GET /api/users/:u/playlists/:slug",
() => fail("Playlist not found", 404), () => fail("Playlist not found", 404),
); );
renderApp(<PlaylistDetail />, { renderPage("/@owner/playlists/x");
route: "/@owner/playlists/x",
path: "/:handle/playlists/:slug",
});
expect(await screen.findByRole("alert")).toHaveTextContent( expect(await screen.findByRole("alert")).toHaveTextContent(
"Playlist not found", "Playlist not found",
); );
@@ -476,7 +457,7 @@ describe("PlaylistDetail", () => {
playlistId: "p1", playlistId: "p1",
userId: "owner", userId: "owner",
}); });
expect(await screen.findByText("home")).toBeInTheDocument(); await waitFor(() => expect(currentPath()).toBe("/"));
}); });
test("deleting the playlist asks, then goes home", async () => { test("deleting the playlist asks, then goes home", async () => {
@@ -492,7 +473,7 @@ describe("PlaylistDetail", () => {
name: "Delete playlist", name: "Delete playlist",
}), }),
); );
expect(await screen.findByText("home")).toBeInTheDocument(); await waitFor(() => expect(currentPath()).toBe("/"));
}); });
test("a refused delete stays and says why", async () => { test("a refused delete stays and says why", async () => {
@@ -537,6 +518,6 @@ describe("PlaylistDetail", () => {
playlistId: "p1", playlistId: "p1",
userId: "owner", userId: "owner",
}); });
expect(await screen.findByText("home")).toBeInTheDocument(); await waitFor(() => expect(currentPath()).toBe("/"));
}); });
}); });

View File

@@ -1,8 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { Route } from "react-router"; import { screen, waitFor } from "@testing-library/react";
import { screen } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Playlists } from "../../pages/Playlists.tsx";
import { calls, route } from "../fetch.ts"; import { calls, route } from "../fetch.ts";
import { import {
makeCategory, makeCategory,
@@ -12,7 +10,7 @@ import {
wire, wire,
} from "../fixtures.ts"; } from "../fixtures.ts";
import type { Session } from "../../utils/auth/storage.ts"; import type { Session } from "../../utils/auth/storage.ts";
import { currentPath, renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts"; import { FakeWebSocket } from "../ws.ts";
const mixes = makeCategory({ const mixes = makeCategory({
@@ -25,13 +23,7 @@ const music = makeCategory({ id: "dc1", slug: "music", name: "Music" });
function open(url: string, session?: Session) { function open(url: string, session?: Session) {
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<Playlists />, { renderPage(url, { categories: [music, mixes], session });
route: url,
path: "/playlists/:categorySlug?",
categories: [music, mixes],
session,
extraRoutes: <Route path="/login" element={null} />,
});
return { user, socket: FakeWebSocket.last }; return { user, socket: FakeWebSocket.last };
} }
@@ -216,9 +208,11 @@ describe("Playlists", () => {
expect(screen.queryByRole("button", { name: "Mine" })).toBeNull(); expect(screen.queryByRole("button", { name: "Mine" })).toBeNull();
}); });
test("a guest sent to their own playlists signs in first", () => { test("a guest sent to their own playlists signs in first", async () => {
open("/playlists?mine=1"); open("/playlists?mine=1");
expect(currentPath()).toBe("/login?next=%2Fplaylists%3Fmine%3D1"); await waitFor(() =>
expect(currentPath()).toBe("/login?next=%2Fplaylists%3Fmine%3D1")
);
}); });
test("a slug that names no playlist category is not found", async () => { test("a slug that names no playlist category is not found", async () => {

View File

@@ -1,19 +1,13 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { screen } from "@testing-library/react"; import { screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Route } from "react-router";
import { ResetPassword } from "../../pages/ResetPassword.tsx";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { renderWithContexts } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
describe("ResetPassword", () => { describe("ResetPassword", () => {
function setup(search = "?token=rst") { function setup(search = "?token=rst") {
const user = userEvent.setup(); const user = userEvent.setup();
renderWithContexts(<ResetPassword />, { renderPage(`/reset-password${search}`);
route: `/reset-password${search}`,
path: "/reset-password",
extraRoutes: <Route path="/login" element={<p>login page</p>} />,
});
return user; return user;
} }
@@ -21,7 +15,7 @@ describe("ResetPassword", () => {
route("POST /api/password-resets", () => ({})); route("POST /api/password-resets", () => ({}));
const user = setup(""); const user = setup("");
await user.type( await user.type(
screen.getByPlaceholderText("Your email address"), await screen.findByPlaceholderText("Your email address"),
" a@b.c {Enter}", " a@b.c {Enter}",
); );
await screen.findByText(/you'll receive a reset link/); await screen.findByText(/you'll receive a reset link/);
@@ -38,7 +32,7 @@ describe("ResetPassword", () => {
route("POST /api/password-resets", () => fail("Internal error", 500)); route("POST /api/password-resets", () => fail("Internal error", 500));
const user = setup(""); const user = setup("");
await user.type( await user.type(
screen.getByPlaceholderText("Your email address"), await screen.findByPlaceholderText("Your email address"),
"a@b.c{Enter}", "a@b.c{Enter}",
); );
expect(await screen.findByRole("alert")).toHaveTextContent( expect(await screen.findByRole("alert")).toHaveTextContent(
@@ -50,7 +44,10 @@ describe("ResetPassword", () => {
test("the two passwords must match", async () => { test("the two passwords must match", async () => {
const user = setup(); const user = setup();
await user.type(screen.getByPlaceholderText("New password"), "longenough"); await user.type(
await screen.findByPlaceholderText("New password"),
"longenough",
);
await user.type( await user.type(
screen.getByPlaceholderText("Confirm new password"), screen.getByPlaceholderText("Confirm new password"),
"different", "different",
@@ -64,7 +61,10 @@ describe("ResetPassword", () => {
test("sets the password, then offers login", async () => { test("sets the password, then offers login", async () => {
route("PUT /api/password-resets/:token", () => ({})); route("PUT /api/password-resets/:token", () => ({}));
const user = setup(); const user = setup();
await user.type(screen.getByPlaceholderText("New password"), "longenough"); await user.type(
await screen.findByPlaceholderText("New password"),
"longenough",
);
await user.type( await user.type(
screen.getByPlaceholderText("Confirm new password"), screen.getByPlaceholderText("Confirm new password"),
"longenough{Enter}", "longenough{Enter}",
@@ -76,7 +76,7 @@ describe("ResetPassword", () => {
newPassword: "longenough", newPassword: "longenough",
}); });
await user.click(screen.getByRole("button", { name: "Go to login" })); await user.click(screen.getByRole("button", { name: "Go to login" }));
expect(screen.getByText("login page")).toBeInTheDocument(); await waitFor(() => expect(currentPath()).toBe("/login"));
}); });
test("an expired token is reported", async () => { test("an expired token is reported", async () => {
@@ -85,7 +85,10 @@ describe("ResetPassword", () => {
() => fail("Reset link expired", 400), () => fail("Reset link expired", 400),
); );
const user = setup(); const user = setup();
await user.type(screen.getByPlaceholderText("New password"), "longenough"); await user.type(
await screen.findByPlaceholderText("New password"),
"longenough",
);
await user.type( await user.type(
screen.getByPlaceholderText("Confirm new password"), screen.getByPlaceholderText("Confirm new password"),
"longenough{Enter}", "longenough{Enter}",

View File

@@ -1,7 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { act, screen, waitFor } from "@testing-library/react"; import { act, screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Search } from "../../pages/Search.tsx";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { import {
makeCategory, makeCategory,
@@ -11,7 +10,7 @@ import {
makeUser, makeUser,
wire, wire,
} from "../fixtures.ts"; } from "../fixtures.ts";
import { currentPath, renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
import { FakeIntersectionObserver } from "../setup.ts"; import { FakeIntersectionObserver } from "../setup.ts";
import { FakeWebSocket } from "../ws.ts"; import { FakeWebSocket } from "../ws.ts";
@@ -40,14 +39,15 @@ function open(
categories: ReturnType<typeof makeCategory>[] = [], categories: ReturnType<typeof makeCategory>[] = [],
) { ) {
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<Search />, { route: url, path: "/search/*", session, categories }); renderPage(url, { session, categories });
return user; return user;
} }
describe("Search", () => { describe("Search", () => {
test("no query: a prompt, no request", () => { test("no query: a prompt, no request", async () => {
open("/search"); open("/search");
expect(screen.getByText("Enter a query to search.")).toBeInTheDocument(); expect(await screen.findByText("Enter a query to search."))
.toBeInTheDocument();
expect(calls("GET /api/search")).toHaveLength(0); expect(calls("GET /api/search")).toHaveLength(0);
}); });

View File

@@ -1,11 +1,10 @@
import { afterEach, describe, expect, test, vi } from "vitest"; import { afterEach, describe, expect, test, vi } from "vitest";
import { screen, waitFor, within } from "@testing-library/react"; import { screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Settings } from "../../pages/Settings.tsx";
import { DEFAULT_SETTINGS } from "../../../shared/settings.ts"; import { DEFAULT_SETTINGS } from "../../../shared/settings.ts";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { makeSession, makeToken } from "../fixtures.ts"; import { makeSession, makeToken } from "../fixtures.ts";
import { renderApp } from "../render.tsx"; import { renderPage } from "../render.tsx";
import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts"; import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts";
import { API_URL } from "../../config/api.ts"; import { API_URL } from "../../config/api.ts";
@@ -32,7 +31,7 @@ const annSession = makeSession({
function open(session = annSession) { function open(session = annSession) {
route("GET /api/me/grants", () => [], { fallback: true }); route("GET /api/me/grants", () => [], { fallback: true });
const user = userEvent.setup(); const user = userEvent.setup();
renderApp(<Settings />, { route: "/settings", path: "/settings", session }); renderPage("/settings", { session });
return user; return user;
} }

View File

@@ -1,18 +1,14 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { screen } from "@testing-library/react"; import { screen } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Unsubscribe } from "../../pages/Unsubscribe.tsx";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { renderWithContexts } from "../render.tsx"; import { renderPage } from "../render.tsx";
import { makeJwt } from "../fixtures.ts"; import { makeJwt } from "../fixtures.ts";
describe("Unsubscribe", () => { describe("Unsubscribe", () => {
function setup(token: string) { function setup(token: string) {
const user = userEvent.setup(); const user = userEvent.setup();
renderWithContexts(<Unsubscribe />, { renderPage(`/unsubscribe?token=${encodeURIComponent(token)}`);
route: `/unsubscribe?token=${encodeURIComponent(token)}`,
path: "/unsubscribe",
});
return user; return user;
} }
@@ -25,7 +21,9 @@ describe("Unsubscribe", () => {
route("POST /api/unsubscribe", () => ({ cadence: "monthly" })); route("POST /api/unsubscribe", () => ({ cadence: "monthly" }));
const user = setup(token); const user = setup(token);
expect( expect(
screen.getByRole("heading", { name: "Turn off the monthly recap?" }), await screen.findByRole("heading", {
name: "Turn off the monthly recap?",
}),
).toBeInTheDocument(); ).toBeInTheDocument();
expect(calls("POST /api/unsubscribe")).toHaveLength(0); expect(calls("POST /api/unsubscribe")).toHaveLength(0);
@@ -49,15 +47,15 @@ describe("Unsubscribe", () => {
makeJwt({ purpose: "unsubscribe", userId: "u", cadence: "weekly" }), makeJwt({ purpose: "unsubscribe", userId: "u", cadence: "weekly" }),
); );
await user.click( await user.click(
screen.getByRole("button", { name: "Turn off weekly digests" }), await screen.findByRole("button", { name: "Turn off weekly digests" }),
); );
expect(await screen.findByText("Invalid unsubscribe link")) expect(await screen.findByText("Invalid unsubscribe link"))
.toBeInTheDocument(); .toBeInTheDocument();
}); });
test("a token that isn't an unsubscribe one is refused before asking", () => { test("a token that isn't an unsubscribe one is refused before asking", async () => {
setup(makeJwt({ purpose: "media", userId: "u" })); setup(makeJwt({ purpose: "media", userId: "u" }));
expect(screen.getByRole("heading", { name: "Invalid link" })) expect(await screen.findByRole("heading", { name: "Invalid link" }))
.toBeInTheDocument(); .toBeInTheDocument();
}); });
}); });

View File

@@ -1,12 +1,10 @@
import { afterEach, describe, expect, test, vi } from "vitest"; import { afterEach, describe, expect, test, vi } from "vitest";
import { screen, waitFor } from "@testing-library/react"; import { screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Route } from "react-router";
import { UserLogin } from "../../pages/UserLogin.tsx";
import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts"; import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts";
import { calls, deferred, fail, route } from "../fetch.ts"; import { calls, deferred, fail, route } from "../fetch.ts";
import { makeSession, wire } from "../fixtures.ts"; import { makeSession, wire } from "../fixtures.ts";
import { currentPath, renderWithContexts } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
const instance = vi.hoisted(() => ({ federationIncoming: true })); const instance = vi.hoisted(() => ({ federationIncoming: true }));
vi.mock("../../config/instance.ts", async (importOriginal) => ({ vi.mock("../../config/instance.ts", async (importOriginal) => ({
@@ -16,16 +14,14 @@ vi.mock("../../config/instance.ts", async (importOriginal) => ({
}, },
})); }));
const home = <Route path="/" element={<p>home page</p>} />; /** Waits for the sign-in to have left the login page for `path`. */
const landsOn = (path: string) =>
waitFor(() => expect(currentPath()).toBe(path));
describe("UserLogin", () => { describe("UserLogin", () => {
function setup() { function setup() {
const user = userEvent.setup(); const user = userEvent.setup();
renderWithContexts(<UserLogin />, { renderPage("/login");
route: "/login",
path: "/login",
extraRoutes: home,
});
return user; return user;
} }
@@ -33,10 +29,10 @@ describe("UserLogin", () => {
const session = makeSession({ username: "ann" }); const session = makeSession({ username: "ann" });
route("POST /api/sessions", () => wire(session)); route("POST /api/sessions", () => wire(session));
const user = setup(); const user = setup();
await user.type(await screen.findByPlaceholderText("Username"), "ann");
expect(document.title).toMatch(/^Log in · /); expect(document.title).toMatch(/^Log in · /);
await user.type(screen.getByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "hunter22{Enter}"); await user.type(screen.getByPlaceholderText("Password"), "hunter22{Enter}");
await screen.findByText("home page"); await landsOn("/");
expect(calls("POST /api/sessions")[0].body).toEqual({ expect(calls("POST /api/sessions")[0].body).toEqual({
username: "ann", username: "ann",
password: "hunter22", password: "hunter22",
@@ -47,6 +43,7 @@ describe("UserLogin", () => {
test("both fields are required", async () => { test("both fields are required", async () => {
const user = setup(); const user = setup();
await screen.findByPlaceholderText("Username");
// The header has a "Log in" button too; this is the form's. // The header has a "Log in" button too; this is the form's.
await user.click( await user.click(
document.querySelector<HTMLButtonElement>( document.querySelector<HTMLButtonElement>(
@@ -54,16 +51,18 @@ describe("UserLogin", () => {
)!, )!,
); );
expect(calls("POST /api/sessions")).toHaveLength(0); expect(calls("POST /api/sessions")).toHaveLength(0);
expect(screen.getByPlaceholderText("Username")).toHaveAttribute( await waitFor(() =>
"aria-invalid", expect(screen.getByPlaceholderText("Username")).toHaveAttribute(
"true", "aria-invalid",
"true",
)
); );
}); });
test("shows the server's refusal", async () => { test("shows the server's refusal", async () => {
route("POST /api/sessions", () => fail("Invalid credentials", 401)); route("POST /api/sessions", () => fail("Invalid credentials", 401));
const user = setup(); const user = setup();
await user.type(screen.getByPlaceholderText("Username"), "ann"); await user.type(await screen.findByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "nope{Enter}"); await user.type(screen.getByPlaceholderText("Password"), "nope{Enter}");
const alert = await screen.findByRole("alert"); const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent("Login failed"); expect(alert).toHaveTextContent("Login failed");
@@ -74,7 +73,7 @@ describe("UserLogin", () => {
test("says when the server can't be reached", async () => { test("says when the server can't be reached", async () => {
route("POST /api/sessions", () => new TypeError("Failed to fetch")); route("POST /api/sessions", () => new TypeError("Failed to fetch"));
const user = setup(); const user = setup();
await user.type(screen.getByPlaceholderText("Username"), "ann"); await user.type(await screen.findByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}"); await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}");
expect(await screen.findByRole("alert")).toHaveTextContent( expect(await screen.findByRole("alert")).toHaveTextContent(
/Could not connect/, /Could not connect/,
@@ -85,7 +84,7 @@ describe("UserLogin", () => {
const pending = deferred(); const pending = deferred();
route("POST /api/sessions", () => pending.promise); route("POST /api/sessions", () => pending.promise);
const user = setup(); const user = setup();
await user.type(screen.getByPlaceholderText("Username"), "ann"); await user.type(await screen.findByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}"); await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}");
expect(await screen.findByRole("button", { name: "Logging in…" })) expect(await screen.findByRole("button", { name: "Logging in…" }))
.toBeDisabled(); .toBeDisabled();
@@ -94,40 +93,31 @@ describe("UserLogin", () => {
JSON.stringify({ success: true, data: wire(makeSession()) }), JSON.stringify({ success: true, data: wire(makeSession()) }),
), ),
); );
await screen.findByText("home page"); await landsOn("/");
}); });
test("Forgot password? leads to the reset page", () => { test("Forgot password? leads to the reset page", async () => {
setup(); setup();
expect(screen.getByRole("link", { name: "Forgot password?" })) expect(await screen.findByRole("link", { name: "Forgot password?" }))
.toHaveAttribute("href", "/reset-password"); .toHaveAttribute("href", "/reset-password");
}); });
test("a sign-in follows ?next= on this site, and only there", async () => { test("a sign-in follows ?next= on this site, and only there", async () => {
route("POST /api/sessions", () => wire(makeSession())); route("POST /api/sessions", () => wire(makeSession()));
const user = userEvent.setup(); const user = userEvent.setup();
renderWithContexts(<UserLogin />, { renderPage(`/login?next=${encodeURIComponent("/authorize?client_id=x")}`);
route: `/login?next=${encodeURIComponent("/authorize?client_id=x")}`, await user.type(await screen.findByPlaceholderText("Username"), "ann");
path: "/login",
extraRoutes: <Route path="/authorize" element={<p>authorize</p>} />,
});
await user.type(screen.getByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}"); await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}");
await screen.findByText("authorize"); await landsOn("/authorize?client_id=x");
expect(currentPath()).toBe("/authorize?client_id=x");
}); });
test("ignores a ?next= that leaves the site", async () => { test("ignores a ?next= that leaves the site", async () => {
route("POST /api/sessions", () => wire(makeSession())); route("POST /api/sessions", () => wire(makeSession()));
const user = userEvent.setup(); const user = userEvent.setup();
renderWithContexts(<UserLogin />, { renderPage(`/login?next=${encodeURIComponent("//evil.example")}`);
route: `/login?next=${encodeURIComponent("//evil.example")}`, await user.type(await screen.findByPlaceholderText("Username"), "ann");
path: "/login",
extraRoutes: home,
});
await user.type(screen.getByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}"); await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}");
await screen.findByText("home page"); await landsOn("/");
}); });
describe("with an account on another instance", () => { describe("with an account on another instance", () => {
@@ -181,10 +171,11 @@ describe("UserLogin", () => {
); );
}); });
test("isn't offered where accounts of other instances don't sign in", () => { test("isn't offered where accounts of other instances don't sign in", async () => {
instance.federationIncoming = false; instance.federationIncoming = false;
setup(); setup();
expect(screen.getByPlaceholderText("Username")).toBeInTheDocument(); expect(await screen.findByPlaceholderText("Username"))
.toBeInTheDocument();
expect(screen.queryByText(/another gerbeur/)).not.toBeInTheDocument(); expect(screen.queryByText(/another gerbeur/)).not.toBeInTheDocument();
expect(calls("GET /api/federation/peers")).toHaveLength(0); expect(calls("GET /api/federation/peers")).toHaveLength(0);
}); });
@@ -197,7 +188,7 @@ describe("UserLogin", () => {
); );
const user = setup(); const user = setup();
await user.type( await user.type(
screen.getByPlaceholderText("Your gerbeur's URL"), await screen.findByPlaceholderText("Your gerbeur's URL"),
"films.example{Enter}", "films.example{Enter}",
); );
expect(await screen.findByRole("alert")).toHaveTextContent( expect(await screen.findByRole("alert")).toHaveTextContent(

View File

@@ -2,7 +2,6 @@ import { API_URL } from "../../config/api.ts";
import { describe, expect, test, vi } from "vitest"; import { describe, expect, test, vi } from "vitest";
import { act, screen, waitFor, within } from "@testing-library/react"; import { act, screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { UserPublicProfile } from "../../pages/UserPublicProfile.tsx";
import type { PublicUser } from "../../../shared/user.ts"; import type { PublicUser } from "../../../shared/user.ts";
import { calls, fail, route } from "../fetch.ts"; import { calls, fail, route } from "../fetch.ts";
import { import {
@@ -14,7 +13,7 @@ import {
page, page,
wire, wire,
} from "../fixtures.ts"; } from "../fixtures.ts";
import { currentPath, renderApp } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts"; import { FakeWebSocket } from "../ws.ts";
import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts"; import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts";
import { FakeIntersectionObserver } from "../setup.ts"; import { FakeIntersectionObserver } from "../setup.ts";
@@ -47,12 +46,7 @@ function open(
route("GET /api/users/:u/upvoted", () => page(votes)); route("GET /api/users/:u/upvoted", () => page(votes));
route("GET /api/users/:u/playlists", () => page(playlists)); route("GET /api/users/:u/playlists", () => page(playlists));
const u = userEvent.setup(); const u = userEvent.setup();
renderApp(<UserPublicProfile />, { renderPage(url, { session, categories });
route: url,
path: "/:handle/*",
session,
categories,
});
return { user: u, socket: FakeWebSocket.last }; return { user: u, socket: FakeWebSocket.last };
} }
@@ -107,10 +101,7 @@ describe("UserPublicProfile", () => {
test("an unknown user", async () => { test("an unknown user", async () => {
route("GET /api/users/:u", () => fail("User not found", 404)); route("GET /api/users/:u", () => fail("User not found", 404));
renderApp(<UserPublicProfile />, { renderPage("/@nobody");
route: "/@nobody",
path: "/:handle/*",
});
expect(await screen.findByRole("alert")).toHaveTextContent( expect(await screen.findByRole("alert")).toHaveTextContent(
"User not found", "User not found",
); );
@@ -133,11 +124,9 @@ describe("UserPublicProfile", () => {
}); });
test("a tab or view the profile hasn't is not found", async () => { test("a tab or view the profile hasn't is not found", async () => {
for (const url of ["/@ann/nope", "/@ann/follow/users", "/@ann/dumps/x"]) { // `/@ann/dumps/x` is a dump's page, not the profile's.
const { unmount } = renderApp(<UserPublicProfile />, { for (const url of ["/@ann/nope", "/@ann/follow/users", "/@ann/dumps/x/y"]) {
route: url, const { unmount } = renderPage(url);
path: "/:handle/*",
});
expect(await screen.findByText("This page does not exist.")) expect(await screen.findByText("This page does not exist."))
.toBeInTheDocument(); .toBeInTheDocument();
unmount(); unmount();

View File

@@ -1,35 +1,31 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { screen } from "@testing-library/react"; import { screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event"; import { userEvent } from "@testing-library/user-event";
import { Route } from "react-router"; import { calls, deferred, fail, route } from "../fetch.ts";
import { UserRegister } from "../../pages/UserRegister.tsx";
import { calls, fail, route } from "../fetch.ts";
import { makeSession, wire } from "../fixtures.ts"; import { makeSession, wire } from "../fixtures.ts";
import { renderWithContexts } from "../render.tsx"; import { currentPath, renderPage } from "../render.tsx";
const home = <Route path="/" element={<p>home page</p>} />;
describe("UserRegister", () => { describe("UserRegister", () => {
function setup(search = "?token=inv-1") { function setup(search = "?token=inv-1") {
const user = userEvent.setup(); const user = userEvent.setup();
renderWithContexts(<UserRegister />, { renderPage(`/register${search}`);
route: `/register${search}`,
path: "/register",
extraRoutes: home,
});
return user; return user;
} }
test("no token: an invalid invite, no request", () => { test("no token: an invalid invite, no request", async () => {
setup(""); setup("");
expect(screen.getByRole("alert")).toHaveTextContent("Invalid invite"); expect(await screen.findByRole("alert")).toHaveTextContent(
"Invalid invite",
);
expect(calls("GET /api/invites/:t")).toHaveLength(0); expect(calls("GET /api/invites/:t")).toHaveLength(0);
}); });
test("an unknown token is invalid", async () => { test("an unknown token is invalid", async () => {
route("GET /api/invites/:t", () => fail("nope", 404)); const invite = deferred();
route("GET /api/invites/:t", () => invite.promise);
setup(); setup();
expect(screen.getByText("Checking invite…")).toBeInTheDocument(); expect(await screen.findByText("Checking invite…")).toBeInTheDocument();
invite.resolve(fail("nope", 404));
expect(await screen.findByRole("alert")).toHaveTextContent("already used"); expect(await screen.findByRole("alert")).toHaveTextContent("already used");
}); });
@@ -44,7 +40,7 @@ describe("UserRegister", () => {
screen.getByPlaceholderText("Password (min. 8 characters)"), screen.getByPlaceholderText("Password (min. 8 characters)"),
"longenough{Enter}", "longenough{Enter}",
); );
await screen.findByText("home page"); await waitFor(() => expect(currentPath()).toBe("/"));
expect(calls("POST /api/users")[0].body).toEqual({ expect(calls("POST /api/users")[0].body).toEqual({
username: "new_one", username: "new_one",
password: "longenough", password: "longenough",

View File

@@ -2,7 +2,13 @@ import { type ReactElement, type ReactNode, useState } from "react";
import { render, type RenderOptions } from "@testing-library/react"; import { render, type RenderOptions } from "@testing-library/react";
import { I18nProvider } from "@lingui/react"; import { I18nProvider } from "@lingui/react";
import { i18n } from "@lingui/core"; import { i18n } from "@lingui/core";
import { MemoryRouter, Route, Routes, useLocation } from "react-router"; import {
type InitialEntry,
MemoryRouter,
Route,
Routes,
useLocation,
} from "react-router";
import type { Session } from "../utils/auth/storage.ts"; import type { Session } from "../utils/auth/storage.ts";
import type { Category } from "../../shared/category.ts"; import type { Category } from "../../shared/category.ts";
@@ -46,6 +52,7 @@ import {
import { PlayerProvider } from "../contexts/player/PlayerProvider.tsx"; import { PlayerProvider } from "../contexts/player/PlayerProvider.tsx";
import { ThemeProvider } from "../contexts/theme/ThemeProvider.tsx"; import { ThemeProvider } from "../contexts/theme/ThemeProvider.tsx";
import { ChatProvider } from "../contexts/chat/ChatProvider.tsx"; import { ChatProvider } from "../contexts/chat/ChatProvider.tsx";
import { AppRoutes } from "../App.tsx";
import { route } from "./fetch.ts"; import { route } from "./fetch.ts";
import { storeSession } from "./fixtures.ts"; import { storeSession } from "./fixtures.ts";
@@ -69,8 +76,11 @@ export function currentPath(): string {
} }
interface RouterOptions { interface RouterOptions {
/** Initial URL, or several for a history stack (the last is current). */ /**
route?: string | string[]; * Initial URL, or several for a history stack (the last is current). An
* entry may be a location, to arrive with the `state` a link hands over.
*/
route?: InitialEntry | InitialEntry[];
/** Route pattern the element is mounted on, for useParams. */ /** Route pattern the element is mounted on, for useParams. */
path?: string; path?: string;
/** Extra routes to mount next to it, e.g. a redirect target. */ /** Extra routes to mount next to it, e.g. a redirect target. */
@@ -277,3 +287,18 @@ export function renderApp(ui: ReactElement, opts: AppOptions = {}) {
); );
return render(ui, { wrapper: Wrapper }); return render(ui, { wrapper: Wrapper });
} }
/**
* Opens `url` as a visit does: `App`'s own route table inside its providers
* (`renderApp`), so the page under test is whichever one the app routes that
* URL to, behind its guard, and a redirect lands on the real page. A page's
* test opens it this way; mounting the page on a pattern typed in the test
* says nothing of whether the app serves that path. Every page is loaded with
* its route, so the first query after it waits (`findBy`, `waitFor`).
*/
export function renderPage(
url: NonNullable<AppOptions["route"]>,
opts: Pick<AppOptions, "session" | "categories"> = {},
) {
return renderApp(<AppRoutes />, { ...opts, route: url });
}