Files
Cato 79c33d3d20 fix(statistics): a gaps topic opens in English (#537)
/statistics/gaps linked to /statistics/gaps/crime.by_background, which answered
404 in English (200 under /de/): the language middleware skips any path with a
dot, taking it for a file. A topic's address is now its key with dots and
underscores as hyphens (/statistics/gaps/crime-by-background); the old key is
still found, so links already shared keep working. Every link to a topic
(index, Find, research sources, the page's own share URL) comes from one
helper.

Tests: slug has no dot and is unique, lookup by slug, key and %2E-escaped key;
render.spec follows every topic link from the index in en and de.

Claude-Session: https://claude.ai/code/session_019MDtms7o5KHhv4niDsxA9M
2026-11-11 14:25:54 +01:00

270 lines
12 KiB
TypeScript

import { test, expect, type Page } from "@playwright/test";
import { EVERYDAY_ROUTES, PRIMARY_NAV, SITE_LINKS } from "../../src/lib/site-config";
import * as enums from "../../src/lib/db/enums";
import en from "../../messages/en.json";
import de from "../../messages/de.json";
/**
* What lint, typecheck and unit tests cannot see: how the site actually
* renders. Every check here is a bug that shipped once.
*
* - `.btn-primary` lost its only definition and every page's main action
* rendered as bare text on production for weeks.
* - The header's six menus wrapped onto two lines at 1440px.
* - A table inside a grid pushed the whole phone layout sideways.
* - The mobile menu opened to nothing: a `fixed` panel inside a header with
* backdrop-filter is positioned against the header, not the screen.
*/
const internal = SITE_LINKS.filter((l) => l.href.startsWith("/"));
test.describe("every page renders", () => {
// The account pages are not in the site map, so they are listed here.
const entry = ["/sign-in", "/sign-up", "/de/sign-up"].map((href) => ({ href }));
for (const link of [{ href: "/" }, ...internal, ...entry]) {
test(`${link.href} answers 200`, async ({ page }) => {
const res = await page.goto(link.href, { waitUntil: "domcontentloaded" });
expect(res?.status()).toBe(200);
});
}
});
// The gaps index's only link answered 404 in English: a topic key's dot made the path look like a
// file to the language middleware, which `/de/…` did not hit (2026-11-10). Follow every topic link.
test("every gaps topic opens from the gaps index, in English and German", async ({ page }) => {
for (const index of ["/statistics/gaps", "/de/statistics/gaps"]) {
await page.goto(index, { waitUntil: "domcontentloaded" });
const hrefs = await page
.locator('main a[href*="/statistics/gaps/"]')
.evaluateAll((as) => as.map((a) => a.getAttribute("href") ?? ""));
expect(hrefs.length, index).toBeGreaterThan(0);
for (const href of hrefs) {
const res = await page.goto(href, { waitUntil: "domcontentloaded" });
expect(res?.status(), href).toBe(200);
}
}
});
// A place the running config has no pack for is not found, never an error:
// production carries no country pack yet, and the CI database holds Testland,
// which only the tests' config knows.
test("an unknown place answers 404", async ({ page }) => {
for (const href of ["/places/nowhere", "/places/testland/northshire", "/de/places/testland"]) {
const res = await page.goto(href, { waitUntil: "domcontentloaded" });
expect(res?.status(), href).toBe(404);
}
});
// An unknown series, law or path answers 404 with a page in the reader's language, inside the site's frame,
// that says what happened and links on: it was an empty page with only a title (2026-11-10).
test("an address Solon does not serve answers a readable 404 page", async ({ page }) => {
for (const [href, title] of [
["/statistics/not-a-series", en.NotFound.title],
["/de/statistics/not-a-series", de.NotFound.title],
["/not-a-page", en.NotFound.title],
["/budgets/not-a-place", en.NotFound.title],
["/de/places/not-a-place", de.NotFound.title],
] as const) {
const res = await page.goto(href, { waitUntil: "domcontentloaded" });
expect(res?.status(), href).toBe(404);
await expect(page.locator("main h1"), href).toHaveText(title);
await expect(page.locator("header nav, nav").first(), href).toBeVisible();
await expect(page.locator('main a[href$="/law"]').first(), href).toBeVisible();
}
});
// A place asked for in a series that has no figure for it says where Solon looked, not only "No figures":
// Liechtenstein's government consumption is empty at the World Bank and absent elsewhere (2026-11-10).
test("a series with no figure for the place asked for says where Solon looked", async ({
page,
}) => {
await page.goto("/statistics/economy-government-consumption?p=LI", {
waitUntil: "domcontentloaded",
});
await expect(
page.getByRole("heading", {
name: en.Statistics.metric.searchTitle.replace("{place}", "Liechtenstein"),
}),
).toBeVisible();
for (const publisher of ["World Bank", "Amt für Statistik", "Eurostat", "OECD"]) {
await expect(page.getByText(publisher, { exact: false }).first(), publisher).toBeVisible();
}
await expect(page.locator('a[href^="https://data.worldbank.org/"]').first()).toBeVisible();
});
// Every value the database stores as a code: OPEN, SIMPLE_MAJORITY, HUMANS_ONLY.
const STORED_CODES = new Set<string>(
(Object.values(enums) as unknown[])
.filter((v): v is unknown[] => Array.isArray(v))
.flat()
.filter((v): v is string => typeof v === "string" && /^[A-Z][A-Z_]+$/.test(v)),
);
// Text a reader actually sees, as written (not as CSS capitalises it), leaving
// out what sits under "Technical details" and code blocks, where codes belong.
async function plainText(page: Page): Promise<string> {
return page.evaluate(() => {
const walker = document.createTreeWalker(document.querySelector("main") ?? document.body, 4);
const out: string[] = [];
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
if (!node.parentElement?.closest("details, pre, code, script, style"))
out.push(node.nodeValue ?? "");
}
return out.join(" ");
});
}
test("the everyday pages show no stored codes", async ({ page }) => {
for (const href of [...EVERYDAY_ROUTES, "/orgs/orangecat"]) {
await page.goto(href, { waitUntil: "domcontentloaded" });
const words = (await plainText(page)).match(/\b[A-Z][A-Z_]{2,}\b/g) ?? [];
expect(
words.filter((w) => STORED_CODES.has(w)),
href,
).toEqual([]);
}
});
async function background(page: Page, selector: string): Promise<string> {
return page
.locator(selector)
.first()
.evaluate((el) => getComputedStyle(el).backgroundColor);
}
test("the primary actions are styled", async ({ page }) => {
await page.goto("/", { waitUntil: "domcontentloaded" });
// A class with no CSS behind it renders transparent — the #77 regression.
expect(await background(page, ".btn-frame-accent")).not.toBe("rgba(0, 0, 0, 0)");
await page.goto("/join", { waitUntil: "domcontentloaded" });
const primary = page.locator(".btn-primary");
if ((await primary.count()) > 0) {
expect(await background(page, ".btn-primary")).not.toBe("rgba(0, 0, 0, 0)");
}
});
test("the header fits on one line at 1440px", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto("/", { waitUntil: "domcontentloaded" });
const { headerHeight, navHeight } = await page.evaluate(() => ({
headerHeight: document.querySelector("header")?.getBoundingClientRect().height ?? 0,
navHeight: parseFloat(
getComputedStyle(document.documentElement).getPropertyValue("--public-nav-height"),
),
}));
expect(headerHeight).toBeGreaterThan(0);
expect(headerHeight).toBeLessThanOrEqual(navHeight + 1);
const header = page.locator("header").first();
for (const item of PRIMARY_NAV) {
const trigger = header.getByRole("button", { name: en.Site.sections[item.key] });
// One line of text. The trigger's own height cannot say so any more: it
// is a 44px touch target (nav contract rule 3), and two lines of 12px
// text fit inside that. Count the label's line boxes instead.
const lines = await trigger.evaluate((el) => {
const range = document.createRange();
range.selectNodeContents(el);
// The chevron is smaller type on the same line, so its box starts a
// few px lower; a wrapped line starts a whole line (~16px) lower.
const tops = [...range.getClientRects()].map((r) => r.top).sort((a, b) => a - b);
return tops.filter((t, i) => i === 0 || t - tops[i - 1] > 8).length;
});
expect(lines).toBe(1);
const b = await trigger.boundingBox();
expect(b?.height ?? 0).toBeGreaterThanOrEqual(44);
}
});
test.describe("phones", () => {
test.use({ viewport: { width: 390, height: 844 } });
for (const href of [
"/",
"/hire",
"/security",
"/governance",
"/proposals",
"/dashboard",
"/sign-up",
]) {
test(`${href} does not scroll sideways`, async ({ page }) => {
await page.goto(href, { waitUntil: "domcontentloaded" });
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - window.innerWidth,
);
expect(overflow).toBeLessThanOrEqual(0);
});
}
// A country open in the atlas: its name, its Law card and its action come
// before the map, so the first screen is not all map. Needs the law data, so
// a database without it (the CI one holds only Testland) skips.
test("an open country shows its name and Law card before the map", async ({ page }) => {
await page.goto("/places?in=li", { waitUntil: "domcontentloaded" });
const law = page.getByRole("heading", { name: en.Atlas.lawTitle, level: 3 });
const shown = await law
.waitFor({ timeout: 20_000 })
.then(() => true)
.catch(() => false);
test.skip(!shown, "the database holds no law for Liechtenstein");
const map = page.getByRole("img", { name: /Liechtenstein/ });
await expect(map).toBeVisible();
const [lawBox, mapBox] = [await law.boundingBox(), await map.boundingBox()];
expect(lawBox!.y).toBeLessThan(mapBox!.y);
expect(lawBox!.y + lawBox!.height).toBeLessThan(844);
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - window.innerWidth,
);
expect(overflow).toBeLessThanOrEqual(0);
});
test("the menu opens and lists the site", async ({ page }) => {
await page.goto("/", { waitUntil: "domcontentloaded" });
const menu = page.locator("#site-menu");
// The page may not have hydrated yet at domcontentloaded, so a first click
// can land on inert HTML. Click only while the menu is still closed.
await expect(async () => {
if (!(await menu.isVisible())) await page.getByRole("button", { name: "Open menu" }).click();
await expect(menu).toBeVisible({ timeout: 1_000 });
}).toPass({ timeout: 20_000 });
const box = await menu.boundingBox();
// It must cover the screen below the header, not collapse inside it.
expect(box?.height ?? 0).toBeGreaterThan(400);
await expect(menu.getByRole("link", { name: "Hire Solon" }).first()).toBeVisible();
// The rest of the site is folded by section (only the current one opens),
// so the menu fits a phone: a section opens, and its pages are there.
await expect(menu.getByRole("link", { name: "Security" })).toBeHidden();
await menu.locator("summary").filter({ hasText: "Platform" }).first().click();
await expect(menu.getByRole("link", { name: "Security" })).toBeVisible();
});
});
/*
* The theme: the device decides until the reader picks one, the pick survives
* a reload, and the head script paints it before the page hydrates (a flash of
* the wrong theme is invisible to every other check).
*/
test.describe("theme", () => {
test.use({ colorScheme: "dark" });
test("follows the device, then the reader's choice, from the first paint", async ({ page }) => {
const theme = () => page.evaluate(() => document.documentElement.dataset.theme);
await page.goto("/security", { waitUntil: "domcontentloaded" });
expect(await theme()).toBe("dark");
const button = page
.locator("header")
.getByRole("button", { name: en.Nav.theme })
.locator("visible=true");
const light = page.getByRole("menuitemradio", { name: en.Nav.themeLight });
// A first click can land before hydration; click only while it is closed.
await expect(async () => {
if (!(await light.isVisible())) await button.click();
await expect(light).toBeVisible({ timeout: 1_000 });
}).toPass({ timeout: 20_000 });
await light.click();
expect(await theme()).toBe("light");
await page.goto("/security", { waitUntil: "commit" });
await page.waitForLoadState("domcontentloaded");
expect(await theme()).toBe("light");
});
});