diff --git a/src/App.tsx b/src/App.tsx
index e5e028b0..6a69d593 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -203,15 +203,22 @@ function HandleRoutes() {
: ;
}
-/** 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 (
<>
} />
+ {
+ /* 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) => (
- } />
+ } />
))}
} />
} />
diff --git a/src/test/App.test.tsx b/src/test/App.test.tsx
new file mode 100644
index 00000000..3c24063e
--- /dev/null
+++ b/src/test/App.test.tsx
@@ -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 | 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("/"));
+ },
+ );
+});
diff --git a/src/test/pages/Authorize.test.tsx b/src/test/pages/Authorize.test.tsx
index fcd30dd3..c4a062dc 100644
--- a/src/test/pages/Authorize.test.tsx
+++ b/src/test/pages/Authorize.test.tsx
@@ -1,11 +1,9 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { screen, waitFor } from "@testing-library/react";
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 { makeSession } from "../fixtures.ts";
-import { currentPath, renderApp } from "../render.tsx";
+import { currentPath, renderPage } from "../render.tsx";
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";
@@ -24,12 +22,7 @@ describe("Authorize", () => {
function open(session = ann) {
const user = userEvent.setup();
- renderApp(, {
- route: `/authorize${QUERY}`,
- path: "/authorize",
- session,
- extraRoutes: login page
} />,
- });
+ renderPage(`/authorize${QUERY}`, { session });
return user;
}
@@ -78,12 +71,8 @@ describe("Authorize", () => {
});
test("a signed-out visitor logs in first and comes back", async () => {
- renderApp(, {
- route: `/authorize${QUERY}`,
- path: "/authorize",
- extraRoutes: login page} />,
- });
- await screen.findByText("login page");
+ renderPage(`/authorize${QUERY}`);
+ await screen.findByRole("heading", { name: "Log in" });
expect(currentPath()).toBe(
`/login?next=${encodeURIComponent(`/authorize${QUERY}`)}`,
);
diff --git a/src/test/pages/Community.test.tsx b/src/test/pages/Community.test.tsx
index a8002a67..1398deef 100644
--- a/src/test/pages/Community.test.tsx
+++ b/src/test/pages/Community.test.tsx
@@ -1,7 +1,6 @@
import { describe, expect, test } from "vitest";
import { screen } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
-import { Community } from "../../pages/Community.tsx";
import { calls, route } from "../fetch.ts";
import {
makeDump,
@@ -10,7 +9,7 @@ import {
makeUser,
wire,
} from "../fixtures.ts";
-import { currentPath, renderApp } from "../render.tsx";
+import { currentPath, renderPage } from "../render.tsx";
function stats(
{
@@ -35,7 +34,7 @@ function stats(
function open(url: string) {
const user = userEvent.setup();
const session = makeSession({ username: "ann" });
- renderApp(, { route: url, path: "/community/*", session });
+ renderPage(url, { session });
return user;
}
diff --git a/src/test/pages/Dump.test.tsx b/src/test/pages/Dump.test.tsx
index 4f83a609..4c2345fd 100644
--- a/src/test/pages/Dump.test.tsx
+++ b/src/test/pages/Dump.test.tsx
@@ -1,10 +1,6 @@
import { describe, expect, test, vi } from "vitest";
import { act, screen, waitFor, within } from "@testing-library/react";
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 {
makeCategory,
@@ -15,7 +11,7 @@ import {
makeUser,
wire,
} from "../fixtures.ts";
-import { currentPath, renderApp } from "../render.tsx";
+import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts";
const owner = makeSession({ id: "owner", username: "owner" });
@@ -48,15 +44,7 @@ function openDump(
url = "/@owner/dumps/a-find",
) {
const user = userEvent.setup();
- renderApp(, {
- route: url,
- path: "/:handle/dumps/:slug",
- session,
- categories: [music],
- extraRoutes: (
- edit page} />
- ),
- });
+ renderPage(url, { session, categories: [music] });
const socket = FakeWebSocket.last;
socket.welcome();
return { user, socket };
@@ -160,7 +148,9 @@ describe("Dump page", () => {
dumpRoutes();
const { user } = openDump(owner);
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 () => {
@@ -268,20 +258,9 @@ describe("Dump page", () => {
({ params }) => wire([params.id === first.id ? second : first]),
);
const user = userEvent.setup();
- renderApp(, {
- route: "/start",
- path: "/:handle/dumps/:slug",
- extraRoutes: (
- open
- }
- />
- ),
- });
+ // Arrived from a card, which hands its dump over with the link.
+ renderPage({ pathname: "/@owner/dumps/a-find", state: { dump: first } });
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: "A find" }));
expect(await screen.findByRole("heading", { name: "A find", level: 1 }))
@@ -455,27 +434,18 @@ describe("DumpEdit page", () => {
function openEdit(dump: ReturnType, session = owner) {
route("GET /api/users/:u/dumps/:slug", () => wire(dump));
const user = userEvent.setup();
- renderApp(
-
-
- ,
- {
- route: `/@owner/dumps/${dump.slug}/edit`,
- path: "/:handle/dumps/:slug/edit",
- session,
- categories: [music],
- extraRoutes: (
- <>
- dump page} />
- home} />
- >
- ),
- },
- );
+ renderPage(`/@owner/dumps/${dump.slug}/edit`, {
+ session,
+ categories: [music],
+ });
FakeWebSocket.last.welcome();
return user;
}
+ /** Waits for the editor to have handed over to a dump's page. */
+ const onDumpPage = () =>
+ waitFor(() => expect(currentPath()).toMatch(/^\/@[^/]+\/dumps\/[^/]+$/));
+
const urlDump = () =>
makeDump({
id: "d1",
@@ -515,7 +485,7 @@ describe("DumpEdit page", () => {
await user.click(screen.getByRole("button", { name: "Music" }));
await user.click(screen.getByRole("button", { name: "Private" }));
await user.click(screen.getByRole("button", { name: "Save" }));
- await screen.findByText("dump page");
+ await onDumpPage();
expect(currentPath()).toBe("/@owner/dumps/new-title");
expect(calls("PUT /api/dumps/:id")[0].body).toEqual({
url: "https://a.test/",
@@ -542,7 +512,7 @@ describe("DumpEdit page", () => {
await user.type(title, "A Find!");
expect(link).toHaveValue("a-find");
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");
});
@@ -572,7 +542,7 @@ describe("DumpEdit page", () => {
const user = openEdit(urlDump());
await user.clear(await screen.findByLabelText("Why?"));
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);
});
@@ -642,7 +612,7 @@ describe("DumpEdit page", () => {
);
await user.click(screen.getByRole("button", { name: "Private" }));
await user.click(screen.getByRole("button", { name: "Save" }));
- await screen.findByText("dump page");
+ await onDumpPage();
const [put] = calls("PUT /api/dumps/:id/file");
const form = put.body as FormData;
expect(form.get("file")).toBeInstanceOf(File);
@@ -676,7 +646,7 @@ describe("DumpEdit page", () => {
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("File too large (max 50 MB)"))
.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")).toHaveLength(0);
});
@@ -719,7 +689,7 @@ describe("DumpEdit page", () => {
name: "Delete dump",
}),
);
- await screen.findByText("home");
+ await waitFor(() => expect(currentPath()).toBe("/"));
expect(
JSON.parse(
document.querySelector('[data-testid="location"]')!.getAttribute(
@@ -760,17 +730,12 @@ describe("DumpEdit page", () => {
expect(await screen.findByText("Not an image")).toBeInTheDocument();
});
- test("guests are sent to log in", () => {
- renderApp(
-
-
- ,
- {
- route: "/@owner/dumps/x/edit",
- path: "/:handle/dumps/:slug/edit",
- extraRoutes: login page} />,
- },
+ test("guests are sent to log in, and back", async () => {
+ renderPage("/@owner/dumps/x/edit");
+ await waitFor(() =>
+ expect(currentPath()).toBe(
+ `/login?next=${encodeURIComponent("/@owner/dumps/x/edit")}`,
+ )
);
- expect(screen.getByText("login page")).toBeInTheDocument();
});
});
diff --git a/src/test/pages/FederationCallback.test.tsx b/src/test/pages/FederationCallback.test.tsx
index 22a1acd2..e6da6cac 100644
--- a/src/test/pages/FederationCallback.test.tsx
+++ b/src/test/pages/FederationCallback.test.tsx
@@ -1,20 +1,14 @@
import { describe, expect, test } from "vitest";
-import { screen } from "@testing-library/react";
-import { Route } from "react-router";
-import { FederationCallback } from "../../pages/FederationCallback.tsx";
+import { screen, waitFor } from "@testing-library/react";
import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts";
import { calls, fail, route } from "../fetch.ts";
-import { makeSession, wire } from "../fixtures.ts";
-import { renderApp } from "../render.tsx";
+import { makeSession, page, wire } from "../fixtures.ts";
+import { currentPath, renderPage } from "../render.tsx";
/** Opens the callback, in a tab that started the sign-in of state `s`. */
function open(query: string, started = "s") {
sessionStorage.setItem("federationState", started);
- renderApp(, {
- route: `/federation/callback${query}`,
- path: "/federation/callback",
- extraRoutes: home page} />,
- });
+ renderPage(`/federation/callback${query}`);
}
describe("FederationCallback", () => {
@@ -23,8 +17,9 @@ describe("FederationCallback", () => {
"POST /api/federation/sessions",
() => wire(makeSession({ username: "alice@home.example" })),
);
+ route("GET /api/dumps", () => page([]));
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(
[{ code: "c", state: "s" }],
);
diff --git a/src/test/pages/Index.test.tsx b/src/test/pages/Index.test.tsx
index 65939031..72b2c932 100644
--- a/src/test/pages/Index.test.tsx
+++ b/src/test/pages/Index.test.tsx
@@ -1,13 +1,6 @@
import { describe, expect, test } from "vitest";
import { act, screen, waitFor, within } from "@testing-library/react";
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 {
makeCategory,
@@ -16,41 +9,19 @@ import {
page,
wire,
} from "../fixtures.ts";
-import { currentPath, renderApp } from "../render.tsx";
+import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts";
import { FakeIntersectionObserver } from "../setup.ts";
const HOUR = 3_600_000;
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 (
-
- );
-}
-
function setup(
url: string,
{ session = null as ReturnType | null } = {},
) {
const user = userEvent.setup();
- renderApp(, {
- route: url,
- path: "*",
- session,
- categories: [music],
- });
+ renderPage(url, { session, categories: [music] });
const socket = FakeWebSocket.last;
socket.welcome();
return { user, socket };
@@ -309,10 +280,12 @@ describe("Index feeds", () => {
.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]));
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 () => {
diff --git a/src/test/pages/Manage.test.tsx b/src/test/pages/Manage.test.tsx
index 66f07658..de75f5c2 100644
--- a/src/test/pages/Manage.test.tsx
+++ b/src/test/pages/Manage.test.tsx
@@ -1,10 +1,9 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
-import { Manage } from "../../pages/Manage.tsx";
import { calls, fail, route } from "../fetch.ts";
import { makeCategory, makeSession, wire } from "../fixtures.ts";
-import { renderApp } from "../render.tsx";
+import { renderPage } from "../render.tsx";
const instance = vi.hoisted(() => ({
federationIncoming: true,
@@ -31,7 +30,7 @@ async function group(label: string) {
function open(session = admin) {
route("GET /api/federation/peers", () => [], { fallback: true });
const user = userEvent.setup();
- renderApp(, { route: "/manage", path: "/manage", session });
+ renderPage("/manage", { session });
return user;
}
diff --git a/src/test/pages/NotFound.test.tsx b/src/test/pages/NotFound.test.tsx
index 3609a33d..3d57446e 100644
--- a/src/test/pages/NotFound.test.tsx
+++ b/src/test/pages/NotFound.test.tsx
@@ -1,12 +1,12 @@
import { describe, expect, test } from "vitest";
import { screen, waitFor } from "@testing-library/react";
-import { NotFound } from "../../pages/NotFound.tsx";
-import { renderWithContexts } from "../render.tsx";
+import { renderPage } from "../render.tsx";
describe("NotFound", () => {
- test("NotFound", async () => {
- renderWithContexts(, { route: "/nope" });
- expect(screen.getByRole("heading", { name: "404" })).toBeInTheDocument();
+ test("a path the app has no page for", async () => {
+ renderPage("/search/users/more");
+ expect(await screen.findByRole("heading", { name: "404" }))
+ .toBeInTheDocument();
await waitFor(() => expect(document.title).toMatch(/^Page not found/));
expect(screen.getByRole("link", { name: "Go home" })).toHaveAttribute(
"href",
diff --git a/src/test/pages/Notifications.test.tsx b/src/test/pages/Notifications.test.tsx
index 850f5e86..89df9309 100644
--- a/src/test/pages/Notifications.test.tsx
+++ b/src/test/pages/Notifications.test.tsx
@@ -1,11 +1,10 @@
import { describe, expect, test, vi } from "vitest";
import { act, screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
-import { Notifications } from "../../pages/Notifications.tsx";
import type { Notification } from "../../../shared/notification.ts";
import { calls, deferred, fail, route } from "../fetch.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 { FakeIntersectionObserver } from "../setup.ts";
@@ -22,10 +21,7 @@ function open(items: Notification[], { hasMore = false } = {}) {
);
route("POST /api/me/notifications/read", () => ({}));
const user = userEvent.setup();
- const view = renderApp(, {
- session: me,
- route: "/notifications",
- });
+ const view = renderPage("/notifications", { session: me });
const socket = FakeWebSocket.last;
socket.welcome({
unreadNotificationCount: items.filter((n) => !n.read).length,
@@ -247,7 +243,7 @@ describe("Notifications", () => {
test("a failed load shows the server's reason", async () => {
route("GET /api/me/notifications", () => fail("Database is locked", 500));
- renderApp(, { session: me });
+ renderPage("/notifications", { session: me });
const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent("Failed to load");
expect(alert).toHaveTextContent("Database is locked");
@@ -303,7 +299,7 @@ describe("Notifications", () => {
const list = deferred();
route("GET /api/me/notifications", () => list.promise);
route("POST /api/me/notifications/read", () => ({}));
- renderApp(, { session: me, route: "/notifications" });
+ renderPage("/notifications", { session: me });
const socket = FakeWebSocket.last;
socket.welcome({ unreadNotificationCount: 1 });
await waitFor(() =>
@@ -343,7 +339,7 @@ describe("Notifications", () => {
: page([n.upvoted], false),
);
route("POST /api/me/notifications/read", () => ({}));
- renderApp(, { session: me });
+ renderPage("/notifications", { session: me });
await screen.findByText(/started following you/);
act(() => FakeIntersectionObserver.instances.at(-1)!.report(true));
expect(await screen.findByText(/^upvoted$/)).toBeInTheDocument();
diff --git a/src/test/pages/PlaylistDetail.test.tsx b/src/test/pages/PlaylistDetail.test.tsx
index b454b628..0af2954c 100644
--- a/src/test/pages/PlaylistDetail.test.tsx
+++ b/src/test/pages/PlaylistDetail.test.tsx
@@ -7,8 +7,6 @@ import {
within,
} from "@testing-library/react";
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 { Playlist } from "../../../shared/playlist.ts";
import { calls, fail, route } from "../fetch.ts";
@@ -19,7 +17,7 @@ import {
makeSession,
wire,
} from "../fixtures.ts";
-import { currentPath, renderApp } from "../render.tsx";
+import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts";
const owner = makeSession({ id: "owner", username: "owner" });
@@ -54,21 +52,7 @@ function open(
() => wire({ ...pl, dumps: items }),
);
const user = userEvent.setup();
- renderApp(, {
- route: url,
- path: "/:handle/playlists/:slug",
- session,
- categories,
- extraRoutes: (
- <>
- home} />
- }
- />
- >
- ),
- });
+ renderPage(url, { session, categories });
const socket = FakeWebSocket.last;
socket.welcome();
return { user, socket, pl };
@@ -103,10 +87,7 @@ describe("PlaylistDetail", () => {
"GET /api/users/:u/playlists/:slug",
() => fail("Playlist not found", 404),
);
- renderApp(, {
- route: "/@owner/playlists/x",
- path: "/:handle/playlists/:slug",
- });
+ renderPage("/@owner/playlists/x");
expect(await screen.findByRole("alert")).toHaveTextContent(
"Playlist not found",
);
@@ -476,7 +457,7 @@ describe("PlaylistDetail", () => {
playlistId: "p1",
userId: "owner",
});
- expect(await screen.findByText("home")).toBeInTheDocument();
+ await waitFor(() => expect(currentPath()).toBe("/"));
});
test("deleting the playlist asks, then goes home", async () => {
@@ -492,7 +473,7 @@ describe("PlaylistDetail", () => {
name: "Delete playlist",
}),
);
- expect(await screen.findByText("home")).toBeInTheDocument();
+ await waitFor(() => expect(currentPath()).toBe("/"));
});
test("a refused delete stays and says why", async () => {
@@ -537,6 +518,6 @@ describe("PlaylistDetail", () => {
playlistId: "p1",
userId: "owner",
});
- expect(await screen.findByText("home")).toBeInTheDocument();
+ await waitFor(() => expect(currentPath()).toBe("/"));
});
});
diff --git a/src/test/pages/Playlists.test.tsx b/src/test/pages/Playlists.test.tsx
index a31f0b24..313a70f8 100644
--- a/src/test/pages/Playlists.test.tsx
+++ b/src/test/pages/Playlists.test.tsx
@@ -1,8 +1,6 @@
import { describe, expect, test } from "vitest";
-import { Route } from "react-router";
-import { screen } from "@testing-library/react";
+import { screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
-import { Playlists } from "../../pages/Playlists.tsx";
import { calls, route } from "../fetch.ts";
import {
makeCategory,
@@ -12,7 +10,7 @@ import {
wire,
} from "../fixtures.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";
const mixes = makeCategory({
@@ -25,13 +23,7 @@ const music = makeCategory({ id: "dc1", slug: "music", name: "Music" });
function open(url: string, session?: Session) {
const user = userEvent.setup();
- renderApp(, {
- route: url,
- path: "/playlists/:categorySlug?",
- categories: [music, mixes],
- session,
- extraRoutes: ,
- });
+ renderPage(url, { categories: [music, mixes], session });
return { user, socket: FakeWebSocket.last };
}
@@ -216,9 +208,11 @@ describe("Playlists", () => {
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");
- 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 () => {
diff --git a/src/test/pages/ResetPassword.test.tsx b/src/test/pages/ResetPassword.test.tsx
index 4038ce63..2269815c 100644
--- a/src/test/pages/ResetPassword.test.tsx
+++ b/src/test/pages/ResetPassword.test.tsx
@@ -1,19 +1,13 @@
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 { Route } from "react-router";
-import { ResetPassword } from "../../pages/ResetPassword.tsx";
import { calls, fail, route } from "../fetch.ts";
-import { renderWithContexts } from "../render.tsx";
+import { currentPath, renderPage } from "../render.tsx";
describe("ResetPassword", () => {
function setup(search = "?token=rst") {
const user = userEvent.setup();
- renderWithContexts(, {
- route: `/reset-password${search}`,
- path: "/reset-password",
- extraRoutes: login page} />,
- });
+ renderPage(`/reset-password${search}`);
return user;
}
@@ -21,7 +15,7 @@ describe("ResetPassword", () => {
route("POST /api/password-resets", () => ({}));
const user = setup("");
await user.type(
- screen.getByPlaceholderText("Your email address"),
+ await screen.findByPlaceholderText("Your email address"),
" a@b.c {Enter}",
);
await screen.findByText(/you'll receive a reset link/);
@@ -38,7 +32,7 @@ describe("ResetPassword", () => {
route("POST /api/password-resets", () => fail("Internal error", 500));
const user = setup("");
await user.type(
- screen.getByPlaceholderText("Your email address"),
+ await screen.findByPlaceholderText("Your email address"),
"a@b.c{Enter}",
);
expect(await screen.findByRole("alert")).toHaveTextContent(
@@ -50,7 +44,10 @@ describe("ResetPassword", () => {
test("the two passwords must match", async () => {
const user = setup();
- await user.type(screen.getByPlaceholderText("New password"), "longenough");
+ await user.type(
+ await screen.findByPlaceholderText("New password"),
+ "longenough",
+ );
await user.type(
screen.getByPlaceholderText("Confirm new password"),
"different",
@@ -64,7 +61,10 @@ describe("ResetPassword", () => {
test("sets the password, then offers login", async () => {
route("PUT /api/password-resets/:token", () => ({}));
const user = setup();
- await user.type(screen.getByPlaceholderText("New password"), "longenough");
+ await user.type(
+ await screen.findByPlaceholderText("New password"),
+ "longenough",
+ );
await user.type(
screen.getByPlaceholderText("Confirm new password"),
"longenough{Enter}",
@@ -76,7 +76,7 @@ describe("ResetPassword", () => {
newPassword: "longenough",
});
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 () => {
@@ -85,7 +85,10 @@ describe("ResetPassword", () => {
() => fail("Reset link expired", 400),
);
const user = setup();
- await user.type(screen.getByPlaceholderText("New password"), "longenough");
+ await user.type(
+ await screen.findByPlaceholderText("New password"),
+ "longenough",
+ );
await user.type(
screen.getByPlaceholderText("Confirm new password"),
"longenough{Enter}",
diff --git a/src/test/pages/Search.test.tsx b/src/test/pages/Search.test.tsx
index ac30e23d..4ea5eed7 100644
--- a/src/test/pages/Search.test.tsx
+++ b/src/test/pages/Search.test.tsx
@@ -1,7 +1,6 @@
import { describe, expect, test } from "vitest";
import { act, screen, waitFor } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
-import { Search } from "../../pages/Search.tsx";
import { calls, fail, route } from "../fetch.ts";
import {
makeCategory,
@@ -11,7 +10,7 @@ import {
makeUser,
wire,
} from "../fixtures.ts";
-import { currentPath, renderApp } from "../render.tsx";
+import { currentPath, renderPage } from "../render.tsx";
import { FakeIntersectionObserver } from "../setup.ts";
import { FakeWebSocket } from "../ws.ts";
@@ -40,14 +39,15 @@ function open(
categories: ReturnType[] = [],
) {
const user = userEvent.setup();
- renderApp(, { route: url, path: "/search/*", session, categories });
+ renderPage(url, { session, categories });
return user;
}
describe("Search", () => {
- test("no query: a prompt, no request", () => {
+ test("no query: a prompt, no request", async () => {
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);
});
diff --git a/src/test/pages/Settings.test.tsx b/src/test/pages/Settings.test.tsx
index a4a0190b..0ee94eed 100644
--- a/src/test/pages/Settings.test.tsx
+++ b/src/test/pages/Settings.test.tsx
@@ -1,11 +1,10 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
-import { Settings } from "../../pages/Settings.tsx";
import { DEFAULT_SETTINGS } from "../../../shared/settings.ts";
import { calls, fail, route } from "../fetch.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 { API_URL } from "../../config/api.ts";
@@ -32,7 +31,7 @@ const annSession = makeSession({
function open(session = annSession) {
route("GET /api/me/grants", () => [], { fallback: true });
const user = userEvent.setup();
- renderApp(, { route: "/settings", path: "/settings", session });
+ renderPage("/settings", { session });
return user;
}
diff --git a/src/test/pages/Unsubscribe.test.tsx b/src/test/pages/Unsubscribe.test.tsx
index 78b20e71..46f17740 100644
--- a/src/test/pages/Unsubscribe.test.tsx
+++ b/src/test/pages/Unsubscribe.test.tsx
@@ -1,18 +1,14 @@
import { describe, expect, test } from "vitest";
import { screen } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
-import { Unsubscribe } from "../../pages/Unsubscribe.tsx";
import { calls, fail, route } from "../fetch.ts";
-import { renderWithContexts } from "../render.tsx";
+import { renderPage } from "../render.tsx";
import { makeJwt } from "../fixtures.ts";
describe("Unsubscribe", () => {
function setup(token: string) {
const user = userEvent.setup();
- renderWithContexts(, {
- route: `/unsubscribe?token=${encodeURIComponent(token)}`,
- path: "/unsubscribe",
- });
+ renderPage(`/unsubscribe?token=${encodeURIComponent(token)}`);
return user;
}
@@ -25,7 +21,9 @@ describe("Unsubscribe", () => {
route("POST /api/unsubscribe", () => ({ cadence: "monthly" }));
const user = setup(token);
expect(
- screen.getByRole("heading", { name: "Turn off the monthly recap?" }),
+ await screen.findByRole("heading", {
+ name: "Turn off the monthly recap?",
+ }),
).toBeInTheDocument();
expect(calls("POST /api/unsubscribe")).toHaveLength(0);
@@ -49,15 +47,15 @@ describe("Unsubscribe", () => {
makeJwt({ purpose: "unsubscribe", userId: "u", cadence: "weekly" }),
);
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"))
.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" }));
- expect(screen.getByRole("heading", { name: "Invalid link" }))
+ expect(await screen.findByRole("heading", { name: "Invalid link" }))
.toBeInTheDocument();
});
});
diff --git a/src/test/pages/UserLogin.test.tsx b/src/test/pages/UserLogin.test.tsx
index 1ed2205d..65360174 100644
--- a/src/test/pages/UserLogin.test.tsx
+++ b/src/test/pages/UserLogin.test.tsx
@@ -1,12 +1,10 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { screen, waitFor } from "@testing-library/react";
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 { calls, deferred, fail, route } from "../fetch.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 }));
vi.mock("../../config/instance.ts", async (importOriginal) => ({
@@ -16,16 +14,14 @@ vi.mock("../../config/instance.ts", async (importOriginal) => ({
},
}));
-const home = home page} />;
+/** Waits for the sign-in to have left the login page for `path`. */
+const landsOn = (path: string) =>
+ waitFor(() => expect(currentPath()).toBe(path));
describe("UserLogin", () => {
function setup() {
const user = userEvent.setup();
- renderWithContexts(, {
- route: "/login",
- path: "/login",
- extraRoutes: home,
- });
+ renderPage("/login");
return user;
}
@@ -33,10 +29,10 @@ describe("UserLogin", () => {
const session = makeSession({ username: "ann" });
route("POST /api/sessions", () => wire(session));
const user = setup();
+ await user.type(await screen.findByPlaceholderText("Username"), "ann");
expect(document.title).toMatch(/^Log in · /);
- await user.type(screen.getByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "hunter22{Enter}");
- await screen.findByText("home page");
+ await landsOn("/");
expect(calls("POST /api/sessions")[0].body).toEqual({
username: "ann",
password: "hunter22",
@@ -47,6 +43,7 @@ describe("UserLogin", () => {
test("both fields are required", async () => {
const user = setup();
+ await screen.findByPlaceholderText("Username");
// The header has a "Log in" button too; this is the form's.
await user.click(
document.querySelector(
@@ -54,16 +51,18 @@ describe("UserLogin", () => {
)!,
);
expect(calls("POST /api/sessions")).toHaveLength(0);
- expect(screen.getByPlaceholderText("Username")).toHaveAttribute(
- "aria-invalid",
- "true",
+ await waitFor(() =>
+ expect(screen.getByPlaceholderText("Username")).toHaveAttribute(
+ "aria-invalid",
+ "true",
+ )
);
});
test("shows the server's refusal", async () => {
route("POST /api/sessions", () => fail("Invalid credentials", 401));
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}");
const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent("Login failed");
@@ -74,7 +73,7 @@ describe("UserLogin", () => {
test("says when the server can't be reached", async () => {
route("POST /api/sessions", () => new TypeError("Failed to fetch"));
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}");
expect(await screen.findByRole("alert")).toHaveTextContent(
/Could not connect/,
@@ -85,7 +84,7 @@ describe("UserLogin", () => {
const pending = deferred();
route("POST /api/sessions", () => pending.promise);
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}");
expect(await screen.findByRole("button", { name: "Logging in…" }))
.toBeDisabled();
@@ -94,40 +93,31 @@ describe("UserLogin", () => {
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();
- expect(screen.getByRole("link", { name: "Forgot password?" }))
+ expect(await screen.findByRole("link", { name: "Forgot password?" }))
.toHaveAttribute("href", "/reset-password");
});
test("a sign-in follows ?next= on this site, and only there", async () => {
route("POST /api/sessions", () => wire(makeSession()));
const user = userEvent.setup();
- renderWithContexts(, {
- route: `/login?next=${encodeURIComponent("/authorize?client_id=x")}`,
- path: "/login",
- extraRoutes: authorize} />,
- });
- await user.type(screen.getByPlaceholderText("Username"), "ann");
+ renderPage(`/login?next=${encodeURIComponent("/authorize?client_id=x")}`);
+ await user.type(await screen.findByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}");
- await screen.findByText("authorize");
- expect(currentPath()).toBe("/authorize?client_id=x");
+ await landsOn("/authorize?client_id=x");
});
test("ignores a ?next= that leaves the site", async () => {
route("POST /api/sessions", () => wire(makeSession()));
const user = userEvent.setup();
- renderWithContexts(, {
- route: `/login?next=${encodeURIComponent("//evil.example")}`,
- path: "/login",
- extraRoutes: home,
- });
- await user.type(screen.getByPlaceholderText("Username"), "ann");
+ renderPage(`/login?next=${encodeURIComponent("//evil.example")}`);
+ await user.type(await screen.findByPlaceholderText("Username"), "ann");
await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}");
- await screen.findByText("home page");
+ await landsOn("/");
});
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;
setup();
- expect(screen.getByPlaceholderText("Username")).toBeInTheDocument();
+ expect(await screen.findByPlaceholderText("Username"))
+ .toBeInTheDocument();
expect(screen.queryByText(/another gerbeur/)).not.toBeInTheDocument();
expect(calls("GET /api/federation/peers")).toHaveLength(0);
});
@@ -197,7 +188,7 @@ describe("UserLogin", () => {
);
const user = setup();
await user.type(
- screen.getByPlaceholderText("Your gerbeur's URL"),
+ await screen.findByPlaceholderText("Your gerbeur's URL"),
"films.example{Enter}",
);
expect(await screen.findByRole("alert")).toHaveTextContent(
diff --git a/src/test/pages/UserPublicProfile.test.tsx b/src/test/pages/UserPublicProfile.test.tsx
index 6236c221..43e7f286 100644
--- a/src/test/pages/UserPublicProfile.test.tsx
+++ b/src/test/pages/UserPublicProfile.test.tsx
@@ -2,7 +2,6 @@ import { API_URL } from "../../config/api.ts";
import { describe, expect, test, vi } from "vitest";
import { act, screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
-import { UserPublicProfile } from "../../pages/UserPublicProfile.tsx";
import type { PublicUser } from "../../../shared/user.ts";
import { calls, fail, route } from "../fetch.ts";
import {
@@ -14,7 +13,7 @@ import {
page,
wire,
} from "../fixtures.ts";
-import { currentPath, renderApp } from "../render.tsx";
+import { currentPath, renderPage } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts";
import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.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/playlists", () => page(playlists));
const u = userEvent.setup();
- renderApp(, {
- route: url,
- path: "/:handle/*",
- session,
- categories,
- });
+ renderPage(url, { session, categories });
return { user: u, socket: FakeWebSocket.last };
}
@@ -107,10 +101,7 @@ describe("UserPublicProfile", () => {
test("an unknown user", async () => {
route("GET /api/users/:u", () => fail("User not found", 404));
- renderApp(, {
- route: "/@nobody",
- path: "/:handle/*",
- });
+ renderPage("/@nobody");
expect(await screen.findByRole("alert")).toHaveTextContent(
"User not found",
);
@@ -133,11 +124,9 @@ describe("UserPublicProfile", () => {
});
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"]) {
- const { unmount } = renderApp(, {
- route: url,
- path: "/:handle/*",
- });
+ // `/@ann/dumps/x` is a dump's page, not the profile's.
+ for (const url of ["/@ann/nope", "/@ann/follow/users", "/@ann/dumps/x/y"]) {
+ const { unmount } = renderPage(url);
expect(await screen.findByText("This page does not exist."))
.toBeInTheDocument();
unmount();
diff --git a/src/test/pages/UserRegister.test.tsx b/src/test/pages/UserRegister.test.tsx
index d0f3d098..5e29b778 100644
--- a/src/test/pages/UserRegister.test.tsx
+++ b/src/test/pages/UserRegister.test.tsx
@@ -1,35 +1,31 @@
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 { Route } from "react-router";
-import { UserRegister } from "../../pages/UserRegister.tsx";
-import { calls, fail, route } from "../fetch.ts";
+import { calls, deferred, fail, route } from "../fetch.ts";
import { makeSession, wire } from "../fixtures.ts";
-import { renderWithContexts } from "../render.tsx";
-
-const home = home page} />;
+import { currentPath, renderPage } from "../render.tsx";
describe("UserRegister", () => {
function setup(search = "?token=inv-1") {
const user = userEvent.setup();
- renderWithContexts(, {
- route: `/register${search}`,
- path: "/register",
- extraRoutes: home,
- });
+ renderPage(`/register${search}`);
return user;
}
- test("no token: an invalid invite, no request", () => {
+ test("no token: an invalid invite, no request", async () => {
setup("");
- expect(screen.getByRole("alert")).toHaveTextContent("Invalid invite");
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Invalid invite",
+ );
expect(calls("GET /api/invites/:t")).toHaveLength(0);
});
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();
- 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");
});
@@ -44,7 +40,7 @@ describe("UserRegister", () => {
screen.getByPlaceholderText("Password (min. 8 characters)"),
"longenough{Enter}",
);
- await screen.findByText("home page");
+ await waitFor(() => expect(currentPath()).toBe("/"));
expect(calls("POST /api/users")[0].body).toEqual({
username: "new_one",
password: "longenough",
diff --git a/src/test/render.tsx b/src/test/render.tsx
index 69052d7c..df74d69e 100644
--- a/src/test/render.tsx
+++ b/src/test/render.tsx
@@ -2,7 +2,13 @@ import { type ReactElement, type ReactNode, useState } from "react";
import { render, type RenderOptions } from "@testing-library/react";
import { I18nProvider } from "@lingui/react";
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 { Category } from "../../shared/category.ts";
@@ -46,6 +52,7 @@ import {
import { PlayerProvider } from "../contexts/player/PlayerProvider.tsx";
import { ThemeProvider } from "../contexts/theme/ThemeProvider.tsx";
import { ChatProvider } from "../contexts/chat/ChatProvider.tsx";
+import { AppRoutes } from "../App.tsx";
import { route } from "./fetch.ts";
import { storeSession } from "./fixtures.ts";
@@ -69,8 +76,11 @@ export function currentPath(): string {
}
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. */
path?: string;
/** 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 });
}
+
+/**
+ * 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,
+ opts: Pick = {},
+) {
+ return renderApp(, { ...opts, route: url });
+}