();
+ }
+
+ vi.stubGlobal("ResizeObserver", MockResizeObserver);
+
+ return { chart, user: userEvent.setup() };
+}
+
+it("renders selection totals, percentages and positive race categories", () => {
+ const { chart } = setup();
+
+ render();
+
+ expect(
+ screen.getByRole("heading", {
+ name: "Recorded race selections",
+ }),
+ ).toBeInTheDocument();
+
+ expect(screen.getByText("1,501")).toBeInTheDocument();
+
+ expect(screen.getByText("Across 2 selected cohorts")).toBeInTheDocument();
+
+ const breakdown = screen.getByRole("list", {
+ name: "Race selection breakdown",
+ });
+
+ const items = within(breakdown).getAllByRole("listitem");
+
+ expect(items).toHaveLength(3);
+
+ const [white, asian, black] = items;
+
+ expect(white).toHaveTextContent("White");
+ expect(white).toHaveTextContent("83.3%");
+ expect(white).toHaveTextContent("1,250");
+
+ expect(asian).toHaveTextContent("Asian");
+ expect(asian).toHaveTextContent("16.7%");
+ expect(asian).toHaveTextContent("250");
+
+ expect(black).toHaveTextContent("Black or African American");
+ expect(black).toHaveTextContent("0.07%");
+
+ expect(
+ within(breakdown).queryByText("American Indian or Alaska Native"),
+ ).not.toBeInTheDocument();
+
+ expect(chart.setOption).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ series: [
+ expect.objectContaining({
+ type: "pie",
+ data: [
+ expect.objectContaining({ name: "White", value: 1250 }),
+ expect.objectContaining({ name: "Asian", value: 250 }),
+ expect.objectContaining({
+ name: "Black or African American",
+ value: 1,
+ }),
+ ],
+ }),
+ ],
+ }),
+ { notMerge: true },
+ );
+
+ expect(
+ screen.getByText(/Each slice is a share of selected race responses/),
+ ).toBeInTheDocument();
+
+ expect(screen.getByRole("figure")).toBeInTheDocument();
+});
+
+it("updates the breakdown and cohort count when data changes", () => {
+ const { chart } = setup();
+
+ const { rerender } = render(
+ ,
+ );
+
+ expect(screen.getByText("125")).toBeInTheDocument();
+
+ const updatedData = [
+ {
+ ...mockRaceDistribution[0],
+ value: 60,
+ },
+ {
+ ...mockRaceDistribution[1],
+ value: 20,
+ },
+ ];
+
+ rerender();
+
+ expect(screen.getByText("Across 1 selected cohort")).toBeInTheDocument();
+
+ expect(screen.getByText("80")).toBeInTheDocument();
+ expect(screen.queryByText("125")).not.toBeInTheDocument();
+
+ const breakdown = screen.getByRole("list", {
+ name: "Race selection breakdown",
+ });
+
+ expect(within(breakdown).getByText("75.0%")).toBeInTheDocument();
+ expect(within(breakdown).getByText("25.0%")).toBeInTheDocument();
+
+ expect(chart.setOption).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ series: [
+ expect.objectContaining({
+ data: [
+ expect.objectContaining({ name: "White", value: 60 }),
+ expect.objectContaining({ name: "Asian", value: 20 }),
+ ],
+ }),
+ ],
+ }),
+ { notMerge: true },
+ );
+});
+
+it("exports the race distribution chart as SVG", async () => {
+ const { chart, user } = setup();
+ const downloads: string[] = [];
+
+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (
+ this: HTMLAnchorElement,
+ ) {
+ downloads.push(this.download);
+ });
+
+ render();
+
+ await user.click(screen.getByRole("button", { name: "Export SVG" }));
+
+ expect(chart.getDataURL).toHaveBeenCalledExactlyOnceWith({
+ type: "svg",
+ backgroundColor: "#ffffff",
+ });
+
+ expect(downloads).toEqual(["race-distribution.svg"]);
+});
+
+it.each([
+ {
+ label: "empty data",
+ rows: [],
+ },
+ {
+ label: "zero selections",
+ rows: [{ ...mockRaceDistribution[0], value: 0 }],
+ },
+])("does not initialize a chart for $label", ({ rows }) => {
+ setup();
+
+ render();
+
+ expect(screen.getByText("0")).toBeInTheDocument();
+
+ const breakdown = screen.getByRole("list", {
+ name: "Race selection breakdown",
+ });
+
+ expect(within(breakdown).queryByRole("listitem")).not.toBeInTheDocument();
+
+ expect(initChart).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/features/races/components/race-chart-options.test.ts b/frontend/src/features/races/components/race-chart-options.test.ts
new file mode 100644
index 0000000..b4cc7b9
--- /dev/null
+++ b/frontend/src/features/races/components/race-chart-options.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from "vitest";
+
+import { getFormatter } from "@/test/chart-utils";
+
+import type { RaceDistributionData } from "../types";
+import {
+ buildRaceChartOptions,
+ getRaceColor,
+ getTotalSelections,
+} from "./race-chart-options";
+
+function row(name: string, value: number): RaceDistributionData {
+ return {
+ name,
+ value,
+ validCount: 1300,
+ unknownCount: 100,
+ missingCount: 100,
+ };
+}
+
+const rows = [
+ row("American Indian or Alaska Native", 0),
+ row("White", 1250),
+ row("Asian", 250),
+];
+
+describe("getRaceColor", () => {
+ it.each([
+ ["White", "#610030"],
+ ["Asian", "#2563eb"],
+ ["Black or African American", "#059669"],
+ ["Native Hawaiian or Other Pacific Islander", "#d97706"],
+ ["American Indian or Alaska Native", "#7c3aed"],
+ ["Other", "#a21caf"],
+ ["𐐀", "#9a3412"],
+ ["", "#be123c"],
+ ["constructor", "#be123c"],
+ ["toString", "#9a3412"],
+ ["__proto__", "#9a3412"],
+ ])("returns the correct color for %s", (name, expected) => {
+ expect(getRaceColor(name)).toBe(expected);
+ });
+});
+
+describe("getTotalSelections", () => {
+ it("sums selections rather than participant counts", () => {
+ expect(getTotalSelections(rows)).toBe(1500);
+ expect(getTotalSelections([])).toBe(0);
+ });
+});
+
+describe("buildRaceChartOptions", () => {
+ it("constructs a chart using positive selection counts", () => {
+ const options = buildRaceChartOptions(rows);
+
+ expect(options.series).toMatchObject([
+ {
+ type: "pie",
+ stillShowZeroSum: false,
+ data: [
+ { name: "White", value: 1250, itemStyle: { color: "#610030" } },
+ { name: "Asian", value: 250, itemStyle: { color: "#2563eb" } },
+ ],
+ },
+ ]);
+
+ expect(options.aria).toMatchObject({
+ enabled: true,
+ label: {
+ description:
+ "Pie chart with 1,500 recorded race selections. " +
+ "Participants may select multiple categories.",
+ },
+ });
+ });
+
+ it.each([{ data: [] }, { data: [row("White", 0)] }])(
+ "handles datasets without selections",
+ ({ data }) => {
+ const options = buildRaceChartOptions(data);
+
+ expect(options.series).toMatchObject([{ data: [] }]);
+ expect(getFormatter(options.tooltip)({ dataIndex: 0 })).toBe("");
+ },
+ );
+});
+
+describe("race tooltip", () => {
+ const format = getFormatter(buildRaceChartOptions(rows).tooltip);
+
+ it.each([
+ { dataIndex: 0, name: "White", count: "1,250", percent: "83.3" },
+ { dataIndex: 1, name: "Asian", count: "250", percent: "16.7" },
+ ])("formats selections for $name", ({ dataIndex, name, count, percent }) => {
+ expect(format({ dataIndex })).toBe(
+ `${name}` +
+ `${count} selections
` +
+ `${percent}% of recorded selections
`,
+ );
+ });
+
+ it("escapes category names and formats small percentages", () => {
+ const options = buildRaceChartOptions([
+ row("White", 999),
+ row(' & "Group"', 1),
+ ]);
+
+ expect(getFormatter(options.tooltip)({ dataIndex: 1 })).toBe(
+ "<Other> & "Group"" +
+ "1 selections
" +
+ "0.1% of recorded selections
",
+ );
+ });
+
+ it.each([null, "invalid", {}, { dataIndex: "0" }, { dataIndex: 99 }])(
+ "rejects invalid tooltip parameters: %j",
+ (params) => {
+ expect(format(params)).toBe("");
+ },
+ );
+});
diff --git a/frontend/src/features/races/components/race-chart-options.ts b/frontend/src/features/races/components/race-chart-options.ts
index a213444..f6399dd 100644
--- a/frontend/src/features/races/components/race-chart-options.ts
+++ b/frontend/src/features/races/components/race-chart-options.ts
@@ -32,7 +32,7 @@ const EXTRA_COLORS = [
] as const;
export function getRaceColor(name: string): string {
- if (COLORS[name]) return COLORS[name];
+ if (Object.hasOwn(COLORS, name)) return COLORS[name];
let hash = 0;
for (const character of name)
hash = (hash * 31 + character.codePointAt(0)!) >>> 0;
diff --git a/frontend/src/features/races/hooks/useRaceDistribution.test.ts b/frontend/src/features/races/hooks/useRaceDistribution.test.ts
new file mode 100644
index 0000000..2312484
--- /dev/null
+++ b/frontend/src/features/races/hooks/useRaceDistribution.test.ts
@@ -0,0 +1,155 @@
+// @vitest-environment jsdom
+
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { expect, it, vi } from "vitest";
+
+import {
+ mockCohorts,
+ mockRaceDistribution,
+ TEST_API_URL,
+} from "@/test/mocks/handlers";
+import { server } from "@/test/mocks/server";
+import { createTestWrapper } from "@/test/render";
+
+import { useRaceDistribution } from "./useRaceDistribution";
+
+const COHORTS_URL = `${TEST_API_URL}/races/cohorts`;
+const DISTRIBUTION_URL = `${TEST_API_URL}/races/distribution`;
+
+function setup() {
+ const { wrapper } = createTestWrapper({ route: null });
+
+ return renderHook(useRaceDistribution, { wrapper });
+}
+
+it("loads all cohorts by default and supports cohort filtering", async () => {
+ const { result } = setup();
+
+ expect(result.current.distributionQuery.fetchStatus).toBe("idle");
+
+ await waitFor(() => {
+ expect(result.current.availableCohorts).toEqual(mockCohorts);
+ expect(result.current.distributionQuery.data).toEqual(mockRaceDistribution);
+ });
+
+ expect(result.current.selectedCohort).toBe("");
+
+ act(() => result.current.selectCohort(" Study A "));
+
+ expect(result.current.selectedCohort).toBe("Study A");
+
+ await waitFor(() => {
+ expect(result.current.distributionQuery.data).toMatchObject([
+ { name: "White", value: 60 },
+ { name: "Asian", value: 20 },
+ ]);
+ });
+
+ act(() => result.current.selectCohort(""));
+
+ expect(result.current.selectedCohort).toBe("");
+
+ await waitFor(() => {
+ expect(result.current.distributionQuery.data).toEqual(mockRaceDistribution);
+ });
+
+ act(() => result.current.selectCohort("Unknown cohort"));
+
+ expect(result.current.selectedCohort).toBe("");
+ expect(result.current.distributionQuery.data).toEqual(mockRaceDistribution);
+});
+
+it("falls back to available cohorts when the selected cohort disappears", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.distributionQuery.isSuccess).toBe(true);
+ });
+
+ act(() => result.current.selectCohort("Study A"));
+
+ await waitFor(() => {
+ expect(result.current.distributionQuery.isSuccess).toBe(true);
+ });
+
+ server.use(http.get(COHORTS_URL, () => HttpResponse.json(["Study B"])));
+
+ await act(async () => {
+ await result.current.cohortsQuery.refetch();
+ });
+
+ await waitFor(() => {
+ expect(result.current.availableCohorts).toEqual(["Study B"]);
+ expect(result.current.selectedCohort).toBe("");
+ expect(result.current.distributionQuery.data).toMatchObject([
+ { name: "White", value: 35 },
+ { name: "Asian", value: 10 },
+ ]);
+ });
+});
+
+it.each([
+ { fail: false, status: "success" },
+ { fail: true, status: "error" },
+])(
+ "disables distribution queries without cohorts ($status)",
+ async ({ fail, status }) => {
+ server.use(
+ http.get(COHORTS_URL, () =>
+ fail ? HttpResponse.error() : HttpResponse.json([]),
+ ),
+ );
+
+ const fetch = vi.spyOn(globalThis, "fetch");
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.cohortsQuery.status).toBe(status);
+ });
+
+ expect(result.current.availableCohorts).toEqual([]);
+ expect(result.current.selectedCohort).toBe("");
+ expect(result.current.distributionQuery.fetchStatus).toBe("idle");
+ expect(result.current.distributionQuery.data).toBeUndefined();
+
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(
+ COHORTS_URL,
+ expect.objectContaining({ method: "GET" }),
+ );
+ },
+);
+
+it("exposes distribution errors and supports retrying", async () => {
+ server.use(
+ http.get(DISTRIBUTION_URL, () =>
+ HttpResponse.json(
+ { detail: "Race distribution unavailable" },
+ { status: 503 },
+ ),
+ ),
+ );
+
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.distributionQuery.isError).toBe(true);
+ });
+
+ expect(result.current.distributionQuery.error?.message).toBe(
+ "Race distribution unavailable",
+ );
+
+ server.use(
+ http.get(DISTRIBUTION_URL, () => HttpResponse.json(mockRaceDistribution)),
+ );
+
+ await act(async () => {
+ await result.current.distributionQuery.refetch();
+ });
+
+ await waitFor(() => {
+ expect(result.current.distributionQuery.isSuccess).toBe(true);
+ expect(result.current.distributionQuery.data).toEqual(mockRaceDistribution);
+ });
+});
diff --git a/frontend/src/features/races/pages/RaceDistributionPage.test.tsx b/frontend/src/features/races/pages/RaceDistributionPage.test.tsx
new file mode 100644
index 0000000..3f8b969
--- /dev/null
+++ b/frontend/src/features/races/pages/RaceDistributionPage.test.tsx
@@ -0,0 +1,346 @@
+// @vitest-environment jsdom
+
+import { act, screen, waitFor, within } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import type { ComponentProps } from "react";
+import { beforeEach, expect, it, vi } from "vitest";
+
+import {
+ mockCohorts,
+ mockRaceDistribution,
+ TEST_API_URL,
+} from "@/test/mocks/handlers";
+import { server } from "@/test/mocks/server";
+import { renderWithProviders } from "@/test/render";
+
+import type { RaceDistributionChart } from "../components/RaceDistributionChart";
+import { raceQueries } from "../queries";
+import { RaceDistributionPage } from "./RaceDistributionPage";
+
+function MockRaceDistributionChart({
+ data,
+ cohortCount,
+}: ComponentProps) {
+ return (
+
+ Selected cohorts: {cohortCount}
+
+
+ {data.map((row) => (
+ -
+ {row.name}: {row.value}
+
+ ))}
+
+
+ );
+}
+
+vi.mock("../components/RaceDistributionChart", () => ({
+ RaceDistributionChart: MockRaceDistributionChart,
+}));
+
+const COHORTS_URL = `${TEST_API_URL}/races/cohorts`;
+const DISTRIBUTION_URL = `${TEST_API_URL}/races/distribution`;
+
+beforeEach(() => {
+ vi.stubGlobal("BASE_UI_ANIMATIONS_DISABLED", true);
+});
+
+function setup() {
+ return renderWithProviders(, {
+ route: null,
+ });
+}
+
+function findChart() {
+ return screen.findByRole("region", {
+ name: "Race distribution chart",
+ });
+}
+
+function failRequest(url: string) {
+ server.use(
+ http.get(url, () =>
+ HttpResponse.json({ detail: "Service unavailable" }, { status: 503 }),
+ ),
+ );
+}
+
+it("loads all cohorts by default and supports filtering and clearing", async () => {
+ let release!: () => void;
+
+ const pending = new Promise((resolve) => {
+ release = resolve;
+ });
+
+ server.use(
+ http.get(DISTRIBUTION_URL, async () => {
+ await pending;
+ return HttpResponse.json(mockRaceDistribution);
+ }),
+ );
+
+ const { user } = setup();
+
+ try {
+ expect(
+ screen.getByRole("heading", {
+ name: "Race Distribution",
+ level: 1,
+ }),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.getByText("Loading cohorts with race data..."),
+ ).toBeInTheDocument();
+
+ expect(
+ await screen.findByText("Loading race distribution..."),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.queryByText("No race selections found"),
+ ).not.toBeInTheDocument();
+ } finally {
+ release();
+ }
+
+ const chart = await findChart();
+
+ expect(within(chart).getByText("Selected cohorts: 2")).toBeInTheDocument();
+
+ expect(within(chart).getByText("White: 95")).toBeInTheDocument();
+ expect(within(chart).getByText("Asian: 30")).toBeInTheDocument();
+
+ const input = screen.getByRole("combobox", { name: "Cohort" });
+
+ expect(input).toHaveValue("");
+ expect(input).toHaveAttribute("placeholder", "All cohorts");
+
+ server.resetHandlers();
+
+ await user.type(input, "Study A");
+
+ await user.click(await screen.findByRole("option", { name: "Study A" }));
+
+ expect(await screen.findByText("White: 60")).toBeInTheDocument();
+
+ const filteredChart = await findChart();
+
+ expect(
+ within(filteredChart).getByText("Selected cohorts: 1"),
+ ).toBeInTheDocument();
+
+ expect(within(filteredChart).getByText("Asian: 20")).toBeInTheDocument();
+
+ expect(input).toHaveValue("Study A");
+
+ await user.click(
+ screen.getByRole("button", { name: "Clear cohort selection" }),
+ );
+
+ expect(await screen.findByText("White: 95")).toBeInTheDocument();
+ expect(screen.getByText("Selected cohorts: 2")).toBeInTheDocument();
+ expect(input).toHaveValue("");
+});
+
+it("recovers from an initial cohort request failure", async () => {
+ failRequest(COHORTS_URL);
+
+ const { user } = setup();
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not load cohorts with race data. Service unavailable",
+ );
+
+ expect(
+ screen.queryByRole("combobox", { name: "Cohort" }),
+ ).not.toBeInTheDocument();
+
+ expect(
+ screen.queryByRole("region", { name: "Selection distribution" }),
+ ).not.toBeInTheDocument();
+
+ server.resetHandlers();
+
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+
+ expect(await findChart()).toBeInTheDocument();
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+});
+
+it("recovers from an initial distribution request failure", async () => {
+ failRequest(DISTRIBUTION_URL);
+
+ const { user } = setup();
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not load race distribution. Service unavailable",
+ );
+
+ expect(screen.getByRole("combobox", { name: "Cohort" })).toBeEnabled();
+
+ expect(
+ screen.queryByText("No race selections found"),
+ ).not.toBeInTheDocument();
+
+ expect(
+ screen.queryByRole("region", { name: "Race distribution chart" }),
+ ).not.toBeInTheDocument();
+
+ server.resetHandlers();
+
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+
+ expect(await findChart()).toBeInTheDocument();
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+});
+
+it("displays an empty state when no cohorts have race data", async () => {
+ server.use(http.get(COHORTS_URL, () => HttpResponse.json([])));
+
+ setup();
+
+ expect(await screen.findByText("No race data available")).toBeInTheDocument();
+
+ expect(
+ screen.queryByRole("combobox", { name: "Cohort" }),
+ ).not.toBeInTheDocument();
+
+ expect(
+ screen.queryByRole("region", { name: "Selection distribution" }),
+ ).not.toBeInTheDocument();
+});
+
+it.each([
+ {
+ label: "empty distribution",
+ rows: [],
+ },
+ {
+ label: "zero selections",
+ rows: [{ ...mockRaceDistribution[0], value: 0 }],
+ },
+])("displays an empty state for $label", async ({ rows }) => {
+ server.use(http.get(DISTRIBUTION_URL, () => HttpResponse.json(rows)));
+
+ setup();
+
+ expect(
+ await screen.findByText("No race selections found"),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.queryByRole("region", { name: "Race distribution chart" }),
+ ).not.toBeInTheDocument();
+
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+});
+
+it("preserves available cohorts when refreshing fails", async () => {
+ const { user, queryClient } = setup();
+
+ const chart = await findChart();
+
+ failRequest(COHORTS_URL);
+
+ await act(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: raceQueries.cohorts().queryKey,
+ });
+ });
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not refresh available cohorts. Showing previously loaded options.",
+ );
+
+ expect(screen.getByRole("combobox", { name: "Cohort" })).toBeEnabled();
+
+ expect(chart).toBeInTheDocument();
+
+ server.resetHandlers();
+
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+
+ await waitFor(() => {
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+
+ expect(chart).toBeInTheDocument();
+});
+
+it.each([
+ {
+ label: "positive selections",
+ rows: mockRaceDistribution,
+ cachedText: "White: 95",
+ },
+ {
+ label: "empty selections",
+ rows: [],
+ cachedText: "No race selections found",
+ },
+])(
+ "preserves cached $label during updates and failed refreshes",
+ async ({ rows, cachedText }) => {
+ server.use(http.get(DISTRIBUTION_URL, () => HttpResponse.json(rows)));
+
+ const { user, queryClient } = setup();
+
+ expect(await screen.findByText(cachedText)).toBeInTheDocument();
+
+ let release!: () => void;
+
+ const pending = new Promise((resolve) => {
+ release = resolve;
+ });
+
+ server.use(
+ http.get(DISTRIBUTION_URL, async () => {
+ await pending;
+
+ return HttpResponse.json(
+ { detail: "Service unavailable" },
+ { status: 503 },
+ );
+ }),
+ );
+
+ try {
+ act(() => {
+ void queryClient.invalidateQueries({
+ queryKey: raceQueries.distribution(mockCohorts).queryKey,
+ });
+ });
+
+ expect(
+ await screen.findByText("Updating race distribution..."),
+ ).toBeInTheDocument();
+
+ expect(screen.getByText(cachedText)).toBeInTheDocument();
+ } finally {
+ release();
+ }
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not refresh race distribution. Showing cached data.",
+ );
+
+ expect(screen.getByText(cachedText)).toBeInTheDocument();
+
+ expect(
+ screen.queryByText("Updating race distribution..."),
+ ).not.toBeInTheDocument();
+
+ server.resetHandlers();
+
+ await user.click(screen.getByRole("button", { name: "Retry refresh" }));
+
+ expect(await findChart()).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+ },
+);
diff --git a/frontend/src/features/races/pages/RaceDistributionPage.tsx b/frontend/src/features/races/pages/RaceDistributionPage.tsx
index a35ad43..14c76f9 100644
--- a/frontend/src/features/races/pages/RaceDistributionPage.tsx
+++ b/frontend/src/features/races/pages/RaceDistributionPage.tsx
@@ -76,7 +76,15 @@ export function RaceDistributionPage() {
width="full"
description="Shares are calculated from selected race responses, not unique participants."
>
- {hasSelections ? (
+ {distributionQuery.isPending ? (
+
+ ) : distributionQuery.isError &&
+ distributionQuery.data === undefined ? (
+ void distributionQuery.refetch()}
+ />
+ ) : (
{distributionQuery.isError && (
)}
+
{distributionQuery.isFetching && (
)}
- }>
- }
+ >
+
+
+ ) : (
+
-
+ )}
- ) : (
-
)}
)}
diff --git a/frontend/src/features/study-picker/api.test.ts b/frontend/src/features/study-picker/api.test.ts
new file mode 100644
index 0000000..1c5ef77
--- /dev/null
+++ b/frontend/src/features/study-picker/api.test.ts
@@ -0,0 +1,59 @@
+import { expect, it, vi } from "vitest";
+
+import {
+ mockRankings,
+ mockVariables,
+ TEST_API_URL,
+} from "@/test/mocks/handlers";
+
+import { fetchStudyPickerVariables, rankCohorts } from "./api";
+
+it("retrieves available variables and forwards the abort signal", async () => {
+ const controller = new AbortController();
+ const fetch = vi.spyOn(globalThis, "fetch");
+
+ await expect(fetchStudyPickerVariables(controller.signal)).resolves.toEqual(
+ mockVariables,
+ );
+
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(
+ `${TEST_API_URL}/study-picker/variables`,
+ expect.objectContaining({
+ method: "GET",
+ signal: controller.signal,
+ }),
+ );
+});
+
+it("normalizes selected variables before requesting rankings", async () => {
+ const controller = new AbortController();
+ const fetch = vi.spyOn(globalThis, "fetch");
+
+ const variables = [" Age ", "Motor score", "Age", "", " ", " Motor score "];
+
+ await expect(rankCohorts(variables, controller.signal)).resolves.toEqual(
+ mockRankings,
+ );
+
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(
+ `${TEST_API_URL}/study-picker/rank`,
+ expect.objectContaining({
+ method: "POST",
+ body: JSON.stringify(["Age", "Motor score"]),
+ signal: controller.signal,
+ }),
+ );
+});
+
+it.each([{ variables: [] }, { variables: ["", " ", "\t", "\n"] }])(
+ "rejects empty selections: $variables",
+ ({ variables }) => {
+ const fetch = vi.spyOn(globalThis, "fetch");
+
+ expect(() => rankCohorts(variables)).toThrow(
+ "Select at least one variable to rank cohorts.",
+ );
+
+ expect(fetch).not.toHaveBeenCalled();
+ },
+);
diff --git a/frontend/src/features/study-picker/components/RankingActions.test.tsx b/frontend/src/features/study-picker/components/RankingActions.test.tsx
new file mode 100644
index 0000000..f9b2957
--- /dev/null
+++ b/frontend/src/features/study-picker/components/RankingActions.test.tsx
@@ -0,0 +1,111 @@
+// @vitest-environment jsdom
+
+import { render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import { expect, it } from "vitest";
+
+import {
+ mockMetadata,
+ mockRankings,
+ mockVariables,
+} from "@/test/mocks/handlers";
+
+import type { RankingRow } from "../utils/ranking";
+import { DataAccessAction, LongitudinalAction } from "./RankingActions";
+
+const row: RankingRow = {
+ ...mockRankings[0],
+ rank: 1,
+ color: mockMetadata["Study A"].color,
+ accessLink: mockMetadata["Study A"].link,
+ availableVariables: mockVariables,
+ longitudinalDataAvailable: true,
+};
+
+it("links to longitudinal availability for matched variables", () => {
+ render(
+
+
+ ,
+ );
+
+ const link = screen.getByRole("link", {
+ name: /View longitudinal measurement availability for Study A/,
+ });
+
+ expect(link).toHaveAttribute(
+ "href",
+ "/plot-longitudinal?cohort=Study+A&variables=Age&variables=Motor+score",
+ );
+
+ expect(link).toHaveAttribute("target", "_blank");
+ expect(link).toHaveAttribute("rel", "noopener noreferrer");
+});
+
+it.each([
+ {
+ longitudinalDataAvailable: false,
+ availableVariables: ["Age"],
+ label: "Data unavailable",
+ title: "Longitudinal data are not available in PDataViewer",
+ },
+ {
+ longitudinalDataAvailable: null,
+ availableVariables: ["Age"],
+ label: "Unknown",
+ title: "Longitudinal data availability could not be determined.",
+ },
+ {
+ longitudinalDataAvailable: true,
+ availableVariables: [],
+ label: "Not available",
+ title: "No longitudinal data match the selected variables.",
+ },
+])(
+ "displays longitudinal availability as $label",
+ ({ longitudinalDataAvailable, availableVariables, label, title }) => {
+ render(
+ ,
+ );
+
+ expect(screen.getByText(label)).toHaveAttribute("title", title);
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ },
+);
+
+it("renders a safe external data access link", () => {
+ render();
+
+ const link = screen.getByRole("link", {
+ name: /Apply for access to Study A/,
+ });
+
+ expect(link).toHaveAttribute("href", "https://example.test/study-a");
+ expect(link).toHaveAttribute("target", "_blank");
+ expect(link).toHaveAttribute("rel", "noopener noreferrer");
+});
+
+it("displays consortium access instead of an external link", () => {
+ render(
+ ,
+ );
+
+ expect(screen.getByText("Consortium access")).toBeInTheDocument();
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+});
+
+it.each([null, "javascript:alert(1)"])(
+ "handles missing or unsafe data access links: %s",
+ (accessLink) => {
+ render();
+
+ expect(screen.getByText("Not available")).toBeInTheDocument();
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ },
+);
diff --git a/frontend/src/features/study-picker/components/RankingCard.test.tsx b/frontend/src/features/study-picker/components/RankingCard.test.tsx
new file mode 100644
index 0000000..06de09c
--- /dev/null
+++ b/frontend/src/features/study-picker/components/RankingCard.test.tsx
@@ -0,0 +1,97 @@
+// @vitest-environment jsdom
+
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { MemoryRouter } from "react-router";
+import { expect, it } from "vitest";
+
+import {
+ mockMetadata,
+ mockRankings,
+ mockVariables,
+} from "@/test/mocks/handlers";
+
+import { prepareRankingRows } from "../utils/ranking";
+import { RankingCard } from "./RankingCard";
+
+const [studyA, studyB] = prepareRankingRows(
+ mockRankings,
+ mockMetadata,
+ mockVariables,
+);
+
+it("renders a fully matched cohort and its available actions", () => {
+ render(
+
+
+ ,
+ );
+
+ expect(screen.getByRole("heading", { name: "Study A" })).toBeInTheDocument();
+
+ expect(screen.getByLabelText("Rank 1")).toHaveTextContent("1");
+ expect(screen.getByText("2/2 (100.0%)")).toBeInTheDocument();
+
+ expect(screen.getByText("All selected variables found")).toBeInTheDocument();
+
+ expect(screen.queryByText("Missing variables")).not.toBeInTheDocument();
+
+ expect(
+ screen.getByRole("link", {
+ name: /View longitudinal measurement availability for Study A/,
+ }),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.getByRole("link", { name: /Apply for access to Study A/ }),
+ ).toBeInTheDocument();
+});
+
+it("renders a partially matched cohort with expandable missing variables", async () => {
+ const user = userEvent.setup();
+
+ render(
+
+
+ ,
+ );
+
+ expect(screen.getByRole("heading", { name: "Study B" })).toBeInTheDocument();
+
+ expect(screen.getByLabelText("Rank 2")).toHaveTextContent("2");
+ expect(screen.getByText("1/2 (50.0%)")).toBeInTheDocument();
+
+ const summary = screen.getByText("Missing variables");
+ const details = summary.closest("details");
+
+ expect(details).not.toHaveAttribute("open");
+
+ await user.click(summary);
+
+ expect(details).toHaveAttribute("open");
+ expect(screen.getByText("Motor score")).toBeVisible();
+
+ await user.click(summary);
+
+ expect(details).not.toHaveAttribute("open");
+
+ expect(
+ screen.getByRole("link", {
+ name: /View longitudinal measurement availability for Study B/,
+ }),
+ ).toHaveAttribute("href", "/plot-longitudinal?cohort=Study+B&variables=Age");
+});
+
+it("renders ranking information without cohort metadata", () => {
+ const [row] = prepareRankingRows([mockRankings[0]], {}, mockVariables);
+
+ render();
+
+ expect(screen.getByRole("heading", { name: "Study A" })).toBeInTheDocument();
+
+ expect(screen.getByText("2/2 (100.0%)")).toBeInTheDocument();
+ expect(screen.getByText("Unknown")).toBeInTheDocument();
+ expect(screen.getByText("Not available")).toBeInTheDocument();
+
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+});
diff --git a/frontend/src/features/study-picker/components/RankingResults.test.tsx b/frontend/src/features/study-picker/components/RankingResults.test.tsx
new file mode 100644
index 0000000..e5a5594
--- /dev/null
+++ b/frontend/src/features/study-picker/components/RankingResults.test.tsx
@@ -0,0 +1,92 @@
+// @vitest-environment jsdom
+
+import { render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { MemoryRouter } from "react-router";
+import { expect, it } from "vitest";
+
+import {
+ mockMetadata,
+ mockRankings,
+ mockVariables,
+} from "@/test/mocks/handlers";
+
+import { RankingResults } from "./RankingResults";
+
+it("renders ranked cohorts and switches between comparison views", async () => {
+ const user = userEvent.setup();
+
+ render(
+
+
+ ,
+ );
+
+ const results = screen.getByRole("region", {
+ name: "Ranked cohorts",
+ });
+
+ const cards = within(results).getAllByRole("article");
+
+ expect(cards).toHaveLength(2);
+
+ expect(
+ cards.map((card) => within(card).getByRole("heading").textContent),
+ ).toEqual(["Study A", "Study B"]);
+
+ const table = within(results).getByRole("table", {
+ name: "Cohorts ranked by variable availability",
+ });
+
+ expect(within(table).getAllByRole("row")).toHaveLength(3);
+
+ const cardContainer = cards[0].parentElement;
+
+ expect(cardContainer).not.toHaveClass("hidden");
+ expect(table.closest(".hidden")).not.toBeNull();
+
+ await user.click(screen.getByRole("button", { name: "Compare in table" }));
+
+ expect(cardContainer).toHaveClass("hidden");
+ expect(table.closest(".hidden")).toBeNull();
+
+ expect(
+ screen.getByText("Swipe horizontally to see all columns."),
+ ).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Show cards" }));
+
+ expect(cardContainer).not.toHaveClass("hidden");
+ expect(table.closest(".hidden")).not.toBeNull();
+
+ expect(
+ screen.queryByText("Swipe horizontally to see all columns."),
+ ).not.toBeInTheDocument();
+
+ expect(
+ screen.getByRole("button", { name: "Compare in table" }),
+ ).toBeInTheDocument();
+});
+
+it("renders an empty state without ranking results", () => {
+ render(
+ ,
+ );
+
+ expect(screen.getByText("No matching cohorts found")).toBeInTheDocument();
+
+ expect(screen.queryByRole("table")).not.toBeInTheDocument();
+ expect(screen.queryByRole("article")).not.toBeInTheDocument();
+
+ expect(
+ screen.queryByRole("button", { name: "Compare in table" }),
+ ).not.toBeInTheDocument();
+});
diff --git a/frontend/src/features/study-picker/components/RankingTable.test.tsx b/frontend/src/features/study-picker/components/RankingTable.test.tsx
new file mode 100644
index 0000000..aeedb8b
--- /dev/null
+++ b/frontend/src/features/study-picker/components/RankingTable.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment jsdom
+
+import { render, screen, within } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import { expect, it } from "vitest";
+
+import type { Metadata } from "@/lib/api/cohorts";
+import {
+ mockMetadata,
+ mockRankings,
+ mockVariables,
+} from "@/test/mocks/handlers";
+
+import { useRankingTable } from "../hooks/useRankingTable";
+import type { RankedCohort } from "../types";
+import { RankingTable } from "./RankingTable";
+
+interface TestTableProps {
+ rankings?: readonly RankedCohort[];
+ metadata?: Metadata;
+}
+
+function TestTable({
+ rankings = mockRankings,
+ metadata = mockMetadata,
+}: TestTableProps) {
+ const table = useRankingTable(rankings, metadata, mockVariables);
+
+ return (
+
+
+
+ );
+}
+
+it("renders ranked cohorts and their variable availability", () => {
+ render();
+
+ const table = screen.getByRole("table", {
+ name: "Cohorts ranked by variable availability",
+ });
+
+ expect(
+ within(table)
+ .getAllByRole("columnheader")
+ .map((header) => header.textContent),
+ ).toEqual([
+ "Cohort (Ranked)",
+ "Variable Match",
+ "Missing Variables",
+ "Longitudinal",
+ "Data Access",
+ ]);
+
+ const rows = within(table).getAllByRole("row").slice(1);
+
+ expect(rows).toHaveLength(2);
+
+ const [rowB, rowA] = rows;
+
+ expect(
+ within(rowB)
+ .getAllByRole("cell")
+ .map((cell) => cell.textContent),
+ ).toEqual([
+ "1Study B",
+ "1/2 (50.0%)",
+ "Motor score",
+ "View availability",
+ "Not available",
+ ]);
+
+ expect(
+ within(rowA)
+ .getAllByRole("cell")
+ .map((cell) => cell.textContent),
+ ).toEqual([
+ "2Study A",
+ "2/2 (100.0%)",
+ "All found",
+ "View availability",
+ "Apply for access",
+ ]);
+
+ expect(
+ within(rowB).getByRole("link", {
+ name: /View longitudinal measurement availability for Study B/,
+ }),
+ ).toHaveAttribute("href", "/plot-longitudinal?cohort=Study+B&variables=Age");
+
+ expect(
+ within(rowA).getByRole("link", {
+ name: /Apply for access to Study A/,
+ }),
+ ).toHaveAttribute("href", "https://example.test/study-a");
+});
+
+it("renders ranking results without cohort metadata", () => {
+ render();
+
+ expect(
+ screen.getByRole("cell", { name: "2/2 (100.0%)" }),
+ ).toBeInTheDocument();
+
+ expect(screen.getByRole("cell", { name: "All found" })).toBeInTheDocument();
+
+ expect(screen.getByRole("cell", { name: "Unknown" })).toBeInTheDocument();
+
+ expect(
+ screen.getByRole("cell", { name: "Not available" }),
+ ).toBeInTheDocument();
+
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+});
+
+it("renders an empty state spanning all columns", () => {
+ render();
+
+ expect(
+ screen.getByRole("cell", {
+ name: "No cohorts matched the selected variables.",
+ }),
+ ).toHaveAttribute("colspan", "5");
+});
diff --git a/frontend/src/features/study-picker/hooks/useRankingTable.test.ts b/frontend/src/features/study-picker/hooks/useRankingTable.test.ts
new file mode 100644
index 0000000..219b592
--- /dev/null
+++ b/frontend/src/features/study-picker/hooks/useRankingTable.test.ts
@@ -0,0 +1,97 @@
+// @vitest-environment jsdom
+
+import { renderHook } from "@testing-library/react";
+import { expect, it } from "vitest";
+
+import type { Metadata } from "@/lib/api/cohorts";
+import {
+ mockMetadata,
+ mockRankings,
+ mockVariables,
+} from "@/test/mocks/handlers";
+
+import type { RankedCohort } from "../types";
+import { useRankingTable } from "./useRankingTable";
+
+interface RankingProps {
+ rankings: readonly RankedCohort[];
+ metadata: Metadata;
+ submittedVariables: readonly string[];
+}
+
+function setup(
+ initialProps: RankingProps = {
+ rankings: mockRankings,
+ metadata: mockMetadata,
+ submittedVariables: mockVariables,
+ },
+) {
+ return renderHook(
+ ({ rankings, metadata, submittedVariables }) =>
+ useRankingTable(rankings, metadata, submittedVariables),
+ { initialProps },
+ );
+}
+
+it("preserves ranking order and uses cohort names as row identifiers", () => {
+ const { result } = setup({
+ rankings: mockRankings.toReversed(),
+ metadata: mockMetadata,
+ submittedVariables: mockVariables,
+ });
+
+ expect(result.current.getRowModel().rows).toMatchObject([
+ {
+ id: "Study B",
+ original: {
+ rank: 1,
+ cohort: "Study B",
+ availableVariables: ["Age"],
+ color: "#059669",
+ },
+ },
+ {
+ id: "Study A",
+ original: {
+ rank: 2,
+ cohort: "Study A",
+ availableVariables: ["Age", "Motor score"],
+ color: "#2563eb",
+ },
+ },
+ ]);
+});
+
+it("updates table rows when ranking inputs change", () => {
+ const { result, rerender } = setup();
+
+ rerender({
+ rankings: [mockRankings[0]],
+ metadata: {},
+ submittedVariables: ["Age"],
+ });
+
+ expect(result.current.getRowModel().rows).toMatchObject([
+ {
+ id: "Study A",
+ original: {
+ rank: 1,
+ cohort: "Study A",
+ availableVariables: ["Age"],
+ color: null,
+ accessLink: null,
+ longitudinalDataAvailable: null,
+ },
+ },
+ ]);
+});
+
+it("handles empty ranking results", () => {
+ const { result } = setup({
+ rankings: [],
+ metadata: mockMetadata,
+ submittedVariables: mockVariables,
+ });
+
+ expect(result.current.getRowModel().rows).toEqual([]);
+});
diff --git a/frontend/src/features/study-picker/hooks/useStudyPicker.test.ts b/frontend/src/features/study-picker/hooks/useStudyPicker.test.ts
new file mode 100644
index 0000000..82980f1
--- /dev/null
+++ b/frontend/src/features/study-picker/hooks/useStudyPicker.test.ts
@@ -0,0 +1,194 @@
+// @vitest-environment jsdom
+
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { expect, it, vi } from "vitest";
+
+import {
+ mockMetadata,
+ mockRankings,
+ mockVariables,
+ TEST_API_URL,
+} from "@/test/mocks/handlers";
+import { server } from "@/test/mocks/server";
+import { createTestWrapper } from "@/test/render";
+
+import { useStudyPicker } from "./useStudyPicker";
+
+const RANK_URL = `${TEST_API_URL}/study-picker/rank`;
+
+function setup() {
+ const { wrapper } = createTestWrapper({ route: null });
+
+ return renderHook(useStudyPicker, { wrapper });
+}
+
+it("loads variables and metadata without requesting rankings", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.availableVariables).toEqual(mockVariables);
+ expect(result.current.metadata).toEqual(mockMetadata);
+ });
+
+ act(() => result.current.submitRanking());
+
+ expect(result.current.selectedVariables).toEqual([]);
+ expect(result.current.submittedVariables).toEqual([]);
+ expect(result.current.rankings).toEqual([]);
+ expect(result.current.canRank).toBe(false);
+ expect(result.current.hasSubmitted).toBe(false);
+ expect(result.current.rankingQuery.fetchStatus).toBe("idle");
+});
+
+it("normalizes selections and manages the ranking lifecycle", async () => {
+ let release!: () => void;
+
+ const pending = new Promise((resolve) => {
+ release = resolve;
+ });
+
+ const rank = vi.fn<() => Promise>(async () => {
+ await pending;
+ return HttpResponse.json(mockRankings);
+ });
+
+ server.use(http.post(RANK_URL, rank));
+
+ const { result } = setup();
+
+ try {
+ await waitFor(() => {
+ expect(result.current.variablesQuery.isSuccess).toBe(true);
+ });
+
+ act(() => {
+ result.current.updateSelectedVariables([
+ " Age ",
+ "Motor score",
+ "Age",
+ "",
+ ]);
+ });
+
+ expect(result.current.selectedVariables).toEqual(mockVariables);
+ expect(result.current.canRank).toBe(true);
+ expect(result.current.hasSubmitted).toBe(false);
+ expect(rank).not.toHaveBeenCalled();
+
+ act(() => result.current.submitRanking());
+
+ await waitFor(() => {
+ expect(result.current.isRanking).toBe(true);
+ expect(rank).toHaveBeenCalledTimes(1);
+ });
+
+ expect(result.current.submittedVariables).toEqual(mockVariables);
+ expect(result.current.hasSubmitted).toBe(true);
+ expect(result.current.canRank).toBe(false);
+ } finally {
+ release();
+ }
+
+ await waitFor(() => {
+ expect(result.current.rankings).toEqual(mockRankings);
+ expect(result.current.isRanking).toBe(false);
+ });
+
+ expect(result.current.canRank).toBe(true);
+
+ // An equivalent selection should preserve the existing results.
+ act(() => {
+ result.current.updateSelectedVariables(["Age", " Motor score ", "Age"]);
+ });
+
+ expect(result.current.submittedVariables).toEqual(mockVariables);
+ expect(result.current.rankings).toEqual(mockRankings);
+
+ // Submitting the same selection should explicitly refetch.
+ act(() => result.current.submitRanking());
+
+ await waitFor(() => {
+ expect(rank).toHaveBeenCalledTimes(2);
+ expect(result.current.isRanking).toBe(false);
+ });
+
+ // Changing the selection should clear the previous submission.
+ act(() => {
+ result.current.updateSelectedVariables(["Motor score", "Age"]);
+ });
+
+ expect(result.current.selectedVariables).toEqual(["Motor score", "Age"]);
+ expect(result.current.submittedVariables).toEqual([]);
+ expect(result.current.rankings).toEqual([]);
+ expect(result.current.hasSubmitted).toBe(false);
+ expect(result.current.canRank).toBe(true);
+});
+
+it("distinguishes empty ranking results from an unsubmitted selection", async () => {
+ server.use(http.post(RANK_URL, () => HttpResponse.json([])));
+
+ const { result } = setup();
+
+ act(() => result.current.updateSelectedVariables(["Age"]));
+ act(() => result.current.submitRanking());
+
+ await waitFor(() => {
+ expect(result.current.rankingQuery.isSuccess).toBe(true);
+ });
+
+ expect(result.current.hasSubmitted).toBe(true);
+ expect(result.current.rankings).toEqual([]);
+});
+
+it("exposes ranking errors and supports retrying", async () => {
+ server.use(
+ http.post(RANK_URL, () =>
+ HttpResponse.json({ detail: "Ranking unavailable" }, { status: 503 }),
+ ),
+ );
+
+ const { result } = setup();
+
+ act(() => result.current.updateSelectedVariables(mockVariables));
+ act(() => result.current.submitRanking());
+
+ await waitFor(() => {
+ expect(result.current.rankingQuery.isError).toBe(true);
+ });
+
+ expect(result.current.rankingQuery.error?.message).toBe(
+ "Ranking unavailable",
+ );
+ expect(result.current.rankings).toEqual([]);
+ expect(result.current.canRank).toBe(true);
+
+ server.use(http.post(RANK_URL, () => HttpResponse.json(mockRankings)));
+
+ act(() => result.current.submitRanking());
+
+ await waitFor(() => {
+ expect(result.current.rankings).toEqual(mockRankings);
+ expect(result.current.rankingQuery.isSuccess).toBe(true);
+ });
+});
+
+it("provides fallback data when initial queries fail", async () => {
+ server.use(
+ http.get(`${TEST_API_URL}/study-picker/variables`, () =>
+ HttpResponse.error(),
+ ),
+ http.get(`${TEST_API_URL}/cohorts/metadata`, () => HttpResponse.error()),
+ );
+
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.variablesQuery.isError).toBe(true);
+ expect(result.current.metadataQuery.isError).toBe(true);
+ });
+
+ expect(result.current.availableVariables).toEqual([]);
+ expect(result.current.metadata).toEqual({});
+ expect(result.current.canRank).toBe(false);
+});
diff --git a/frontend/src/features/study-picker/pages/StudyPickerPage.test.tsx b/frontend/src/features/study-picker/pages/StudyPickerPage.test.tsx
new file mode 100644
index 0000000..bf8a4b6
--- /dev/null
+++ b/frontend/src/features/study-picker/pages/StudyPickerPage.test.tsx
@@ -0,0 +1,307 @@
+// @vitest-environment jsdom
+
+import { screen, waitFor, within } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { beforeEach, expect, it, vi } from "vitest";
+
+import { mockRankings, TEST_API_URL } from "@/test/mocks/handlers";
+import { server } from "@/test/mocks/server";
+import { renderWithProviders } from "@/test/render";
+
+import { StudyPickerPage } from "./StudyPickerPage";
+
+const VARIABLES_URL = `${TEST_API_URL}/study-picker/variables`;
+const RANK_URL = `${TEST_API_URL}/study-picker/rank`;
+
+type TestUser = ReturnType["user"];
+
+beforeEach(() => {
+ vi.stubGlobal("BASE_UI_ANIMATIONS_DISABLED", true);
+});
+
+function setup() {
+ return renderWithProviders();
+}
+
+async function selectVariable(user: TestUser, variable: string) {
+ const input = screen.getByRole("combobox", {
+ name: "Variables of interest",
+ });
+
+ await waitFor(() => {
+ expect(input).toBeEnabled();
+ });
+
+ await user.clear(input);
+ await user.type(input, variable);
+
+ await user.click(await screen.findByRole("option", { name: variable }));
+
+ await user.keyboard("{Escape}");
+}
+
+function findRankingTable() {
+ return screen.findByRole("table", {
+ name: "Cohorts ranked by variable availability",
+ });
+}
+
+function failRanking() {
+ server.use(
+ http.post(RANK_URL, () =>
+ HttpResponse.json({ detail: "Ranking unavailable" }, { status: 503 }),
+ ),
+ );
+}
+
+it("selects variables, submits rankings and invalidates outdated results", async () => {
+ let release!: () => void;
+
+ const pending = new Promise((resolve) => {
+ release = resolve;
+ });
+
+ server.use(
+ http.post(RANK_URL, async () => {
+ await pending;
+ return HttpResponse.json(mockRankings);
+ }),
+ );
+
+ const { user } = setup();
+
+ expect(
+ screen.getByRole("heading", { name: "Study Picker", level: 1 }),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.getByRole("combobox", { name: "Variables of interest" }),
+ ).toBeDisabled();
+
+ expect(screen.getByText("Loading available options.")).toBeInTheDocument();
+
+ const rankButton = screen.getByRole("button", {
+ name: "Rank cohorts",
+ });
+
+ expect(rankButton).toBeDisabled();
+
+ await selectVariable(user, "Age");
+ await selectVariable(user, "Motor score");
+
+ expect(screen.getByText("2 selected")).toBeInTheDocument();
+ expect(rankButton).toBeEnabled();
+
+ expect(
+ screen.queryByRole("region", { name: "Cohort ranking results" }),
+ ).not.toBeInTheDocument();
+
+ try {
+ await user.click(rankButton);
+
+ expect(
+ await screen.findByText("Calculating cohort rankings..."),
+ ).toBeInTheDocument();
+
+ expect(screen.getByText("Ranking cohorts...")).toBeInTheDocument();
+ expect(rankButton).toBeDisabled();
+ } finally {
+ release();
+ }
+
+ const table = await findRankingTable();
+
+ expect(
+ within(table).getByRole("cell", { name: "2/2 (100.0%)" }),
+ ).toBeInTheDocument();
+
+ expect(
+ within(table).getByRole("cell", { name: "1/2 (50.0%)" }),
+ ).toBeInTheDocument();
+
+ expect(
+ await within(table).findByRole("link", {
+ name: /View longitudinal measurement availability for Study A/,
+ }),
+ ).toHaveAttribute(
+ "href",
+ "/plot-longitudinal?cohort=Study+A&variables=Age&variables=Motor+score",
+ );
+
+ expect(rankButton).toBeEnabled();
+
+ // Changing the selection removes the previous ranking.
+ await user.click(screen.getByRole("button", { name: "Remove Motor score" }));
+
+ expect(screen.getByText("1 selected")).toBeInTheDocument();
+
+ expect(
+ screen.queryByRole("region", { name: "Cohort ranking results" }),
+ ).not.toBeInTheDocument();
+
+ server.resetHandlers();
+
+ await user.click(rankButton);
+
+ const updatedTable = await findRankingTable();
+
+ expect(
+ within(updatedTable).getAllByRole("cell", {
+ name: "1/1 (100.0%)",
+ }),
+ ).toHaveLength(2);
+
+ expect(
+ within(updatedTable).getByRole("link", {
+ name: /View longitudinal measurement availability for Study A/,
+ }),
+ ).toHaveAttribute("href", "/plot-longitudinal?cohort=Study+A&variables=Age");
+
+ await user.click(screen.getByRole("button", { name: "Clear all" }));
+
+ expect(rankButton).toBeDisabled();
+
+ expect(
+ screen.queryByRole("region", { name: "Cohort ranking results" }),
+ ).not.toBeInTheDocument();
+});
+
+it("recovers from a variable request failure", async () => {
+ server.use(
+ http.get(VARIABLES_URL, () =>
+ HttpResponse.json({ detail: "Variables unavailable" }, { status: 503 }),
+ ),
+ );
+
+ const { user } = setup();
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not load available variables. Variables unavailable",
+ );
+
+ const input = screen.getByRole("combobox", {
+ name: "Variables of interest",
+ });
+
+ expect(input).toBeDisabled();
+
+ server.resetHandlers();
+
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+
+ await waitFor(() => {
+ expect(input).toBeEnabled();
+ });
+
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+});
+
+it("recovers from an initial ranking failure", async () => {
+ failRanking();
+
+ const { user } = setup();
+
+ await selectVariable(user, "Age");
+
+ await user.click(screen.getByRole("button", { name: "Rank cohorts" }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not retrieve cohort rankings. Ranking unavailable",
+ );
+
+ expect(screen.queryByRole("table")).not.toBeInTheDocument();
+
+ expect(
+ screen.queryByText("No matching cohorts found"),
+ ).not.toBeInTheDocument();
+
+ server.resetHandlers();
+
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+
+ expect(await findRankingTable()).toBeInTheDocument();
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+});
+
+it("preserves cached rankings when resubmitting the same selection fails", async () => {
+ const { user } = setup();
+
+ await selectVariable(user, "Age");
+
+ await user.click(screen.getByRole("button", { name: "Rank cohorts" }));
+
+ const table = await findRankingTable();
+
+ failRanking();
+
+ await user.click(screen.getByRole("button", { name: "Rank cohorts" }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not retrieve cohort rankings. Ranking unavailable",
+ );
+
+ expect(table).toBeInTheDocument();
+
+ expect(
+ within(table).getAllByRole("cell", { name: "1/1 (100.0%)" }),
+ ).toHaveLength(2);
+
+ server.resetHandlers();
+
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+
+ await waitFor(() => {
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+
+ expect(table).toBeInTheDocument();
+});
+
+it("displays an empty state when no cohorts match", async () => {
+ server.use(http.post(RANK_URL, () => HttpResponse.json([])));
+
+ const { user } = setup();
+
+ await selectVariable(user, "Age");
+
+ await user.click(screen.getByRole("button", { name: "Rank cohorts" }));
+
+ expect(
+ await screen.findByText("No matching cohorts found"),
+ ).toBeInTheDocument();
+
+ expect(screen.queryByRole("table")).not.toBeInTheDocument();
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+});
+
+it("renders rankings when cohort metadata is unavailable", async () => {
+ server.use(
+ http.get(`${TEST_API_URL}/cohorts/metadata`, () =>
+ HttpResponse.json({ detail: "Metadata unavailable" }, { status: 503 }),
+ ),
+ );
+
+ const { user } = setup();
+
+ await selectVariable(user, "Age");
+
+ await user.click(screen.getByRole("button", { name: "Rank cohorts" }));
+
+ expect(
+ await screen.findByText(
+ "Cohort metadata could not be loaded. Some colors and data-access links may be unavailable.",
+ ),
+ ).toBeInTheDocument();
+
+ const table = await findRankingTable();
+
+ expect(within(table).getAllByRole("cell", { name: "Unknown" })).toHaveLength(
+ 2,
+ );
+
+ expect(
+ within(table).getAllByRole("cell", { name: "Not available" }),
+ ).toHaveLength(2);
+
+ expect(within(table).queryByRole("link")).not.toBeInTheDocument();
+});
diff --git a/frontend/src/features/study-picker/utils/ranking.test.ts b/frontend/src/features/study-picker/utils/ranking.test.ts
new file mode 100644
index 0000000..ecd7580
--- /dev/null
+++ b/frontend/src/features/study-picker/utils/ranking.test.ts
@@ -0,0 +1,256 @@
+import { describe, expect, it } from "vitest";
+
+import { mockMetadata, mockRankings } from "@/test/mocks/handlers";
+
+import {
+ getLongitudinalHref,
+ prepareRankingRows,
+ type RankingRow,
+} from "./ranking";
+
+const submittedVariables = ["Age", "Motor score"];
+
+const sampleRow: RankingRow = {
+ cohort: "Study A",
+ found: "2/2 (100.0%)",
+ missing: "",
+ rank: 1,
+ color: "#2563eb",
+ accessLink: "https://example.test/study-a",
+ availableVariables: ["Age", "Motor score"],
+ longitudinalDataAvailable: true,
+};
+
+describe("prepareRankingRows", () => {
+ it("enriches ranking results with cohort metadata", () => {
+ const rows = prepareRankingRows(
+ mockRankings,
+ mockMetadata,
+ submittedVariables,
+ );
+
+ expect(rows).toEqual([
+ sampleRow,
+ {
+ cohort: "Study B",
+ found: "1/2 (50.0%)",
+ missing: "Motor score",
+ rank: 2,
+ color: "#059669",
+ accessLink: null,
+ availableVariables: ["Age"],
+ longitudinalDataAvailable: true,
+ },
+ ]);
+ });
+
+ it("preserves the ranking order returned by the backend", () => {
+ const rankings = mockRankings.toReversed();
+
+ const rows = prepareRankingRows(rankings, mockMetadata, submittedVariables);
+
+ expect(rows.map(({ cohort, rank }) => ({ cohort, rank }))).toEqual([
+ { cohort: "Study B", rank: 1 },
+ { cohort: "Study A", rank: 2 },
+ ]);
+ });
+
+ it("handles missing cohort metadata", () => {
+ const rows = prepareRankingRows(
+ [
+ {
+ cohort: "Unknown study",
+ found: "1/1 (100.0%)",
+ missing: "",
+ },
+ ],
+ mockMetadata,
+ ["Age"],
+ );
+
+ expect(rows).toEqual([
+ {
+ cohort: "Unknown study",
+ found: "1/1 (100.0%)",
+ missing: "",
+ rank: 1,
+ color: null,
+ accessLink: null,
+ availableVariables: ["Age"],
+ longitudinalDataAvailable: null,
+ },
+ ]);
+ });
+
+ it("preserves explicitly unavailable longitudinal data", () => {
+ const metadata = {
+ ...mockMetadata,
+ "Study A": {
+ ...mockMetadata["Study A"],
+ longitudinalDataAvailable: false,
+ },
+ };
+
+ const rows = prepareRankingRows(mockRankings, metadata, submittedVariables);
+
+ expect(rows[0]?.longitudinalDataAvailable).toBe(false);
+ expect(rows[1]?.longitudinalDataAvailable).toBe(true);
+ });
+
+ it.each([
+ {
+ missing: "",
+ found: "3/3 (100.0%)",
+ expected: ["Age", "Motor score", "Sex"],
+ },
+ {
+ missing: "Motor score",
+ found: "2/3 (66.67%)",
+ expected: ["Age", "Sex"],
+ },
+ {
+ missing: "Age, Motor score, Sex",
+ found: "0/3 (0.0%)",
+ expected: [],
+ },
+ {
+ missing: " Motor score , , Motor score, Age ",
+ found: "1/3 (33.33%)",
+ expected: ["Sex"],
+ },
+ ])(
+ "determines available variables for missing values: $missing",
+ ({ missing, found, expected }) => {
+ const rows = prepareRankingRows(
+ [
+ {
+ cohort: "Study A",
+ found,
+ missing,
+ },
+ ],
+ mockMetadata,
+ ["Age", "Motor score", "Sex"],
+ );
+
+ expect(rows[0]?.availableVariables).toEqual(expected);
+ },
+ );
+
+ it("returns no rows for empty ranking results", () => {
+ expect(prepareRankingRows([], mockMetadata, submittedVariables)).toEqual(
+ [],
+ );
+ });
+
+ it("handles an empty submitted variable selection", () => {
+ const rows = prepareRankingRows(mockRankings, mockMetadata, []);
+
+ expect(rows.map((row) => row.availableVariables)).toEqual([[], []]);
+ });
+
+ it("does not mutate the supplied ranking data or variables", () => {
+ const ranking = Object.freeze({
+ cohort: "Study A",
+ found: "1/2 (50.0%)",
+ missing: "Motor score",
+ });
+
+ const rankings = Object.freeze([ranking]);
+ const variables = Object.freeze(["Age", "Motor score"]);
+
+ const metadata = Object.freeze({
+ "Study A": Object.freeze({
+ ...mockMetadata["Study A"],
+ }),
+ });
+
+ const rows = prepareRankingRows(rankings, metadata, variables);
+
+ expect(rows[0]).not.toBe(ranking);
+
+ expect(rows[0]?.availableVariables).toEqual(["Age"]);
+
+ expect(rankings).toEqual([
+ {
+ cohort: "Study A",
+ found: "1/2 (50.0%)",
+ missing: "Motor score",
+ },
+ ]);
+
+ expect(variables).toEqual(["Age", "Motor score"]);
+ });
+});
+
+describe("getLongitudinalHref", () => {
+ it("constructs a URL containing all available variables", () => {
+ expect(getLongitudinalHref(sampleRow)).toBe(
+ "/plot-longitudinal?cohort=Study+A&variables=Age&variables=Motor+score",
+ );
+ });
+
+ it("supports a single available variable", () => {
+ const row: RankingRow = {
+ ...sampleRow,
+ availableVariables: ["Age"],
+ };
+
+ expect(getLongitudinalHref(row)).toBe(
+ "/plot-longitudinal?cohort=Study+A&variables=Age",
+ );
+ });
+
+ it("correctly encodes special characters and Unicode", () => {
+ const row: RankingRow = {
+ ...sampleRow,
+ cohort: "Study A & B (München)",
+ availableVariables: [
+ "UPDRS III / Total Score",
+ "Age + follow-up",
+ "α-synuclein (%)",
+ ],
+ };
+
+ const href = getLongitudinalHref(row);
+
+ expect(href).not.toBeNull();
+
+ const url = new URL(href ?? "", "https://example.test");
+
+ expect(url.pathname).toBe("/plot-longitudinal");
+
+ expect(url.searchParams.get("cohort")).toBe("Study A & B (München)");
+
+ expect(url.searchParams.getAll("variables")).toEqual([
+ "UPDRS III / Total Score",
+ "Age + follow-up",
+ "α-synuclein (%)",
+ ]);
+ });
+
+ it.each([
+ {
+ longitudinalDataAvailable: false,
+ availableVariables: ["Age"],
+ },
+ {
+ longitudinalDataAvailable: null,
+ availableVariables: ["Age"],
+ },
+ {
+ longitudinalDataAvailable: true,
+ availableVariables: [],
+ },
+ ])(
+ "returns no URL when longitudinal navigation is unavailable: %j",
+ (overrides) => {
+ const row: RankingRow = {
+ ...sampleRow,
+ ...overrides,
+ };
+
+ expect(getLongitudinalHref(row)).toBeNull();
+ },
+ );
+});
diff --git a/frontend/src/hooks/useECharts.test.tsx b/frontend/src/hooks/useECharts.test.tsx
new file mode 100644
index 0000000..14bf5f8
--- /dev/null
+++ b/frontend/src/hooks/useECharts.test.tsx
@@ -0,0 +1,180 @@
+// @vitest-environment jsdom
+
+import { render, renderHook, screen } from "@testing-library/react";
+import type { EChartsCoreOption, EChartsType } from "echarts/core";
+import { expect, it, vi } from "vitest";
+
+import { useECharts } from "./useECharts";
+
+type ChartDouble = ReturnType;
+
+const initChart = vi.hoisted(() => vi.fn<() => ChartDouble>());
+
+vi.mock("echarts/core", () => ({
+ init: initChart,
+}));
+
+const INITIAL_OPTIONS: EChartsCoreOption = { series: [] };
+const UPDATED_OPTIONS: EChartsCoreOption = {
+ title: { text: "Updated chart" },
+};
+
+function createChart() {
+ return {
+ setOption: vi.fn(),
+ resize: vi.fn(),
+ isDisposed: vi.fn(() => false),
+ dispose: vi.fn(),
+ };
+}
+
+function setup() {
+ const chart = createChart();
+
+ initChart.mockReset().mockReturnValue(chart);
+
+ const observe = vi.fn();
+ const disconnect = vi.fn();
+
+ let notify: (() => void) | undefined;
+
+ class MockResizeObserver implements ResizeObserver {
+ constructor(callback: ResizeObserverCallback) {
+ notify = () => callback([], this);
+ }
+
+ observe = observe;
+ disconnect = disconnect;
+ unobserve = vi.fn();
+ }
+
+ vi.stubGlobal("ResizeObserver", MockResizeObserver);
+
+ return {
+ chart,
+ observe,
+ disconnect,
+ notifyResize: () => {
+ if (!notify) {
+ throw new Error("ResizeObserver has not been initialized");
+ }
+
+ notify();
+ },
+ };
+}
+
+interface ChartProbeProps {
+ options: EChartsCoreOption;
+ enabled?: boolean;
+}
+
+function ChartProbe({ options, enabled }: ChartProbeProps) {
+ const { containerRef } = useECharts(options, { enabled });
+
+ return ;
+}
+
+it("does not initialize without a container", () => {
+ setup();
+
+ const { result } = renderHook(() => useECharts(INITIAL_OPTIONS));
+
+ expect(result.current.chartRef.current).toBeNull();
+ expect(initChart).not.toHaveBeenCalled();
+});
+
+it("initializes, updates, disables and recreates the chart", () => {
+ const { chart, observe, disconnect } = setup();
+
+ const { rerender, unmount } = render(
+ ,
+ );
+
+ expect(initChart).not.toHaveBeenCalled();
+
+ rerender();
+
+ const container = screen.getByTestId("chart");
+
+ expect(initChart).toHaveBeenCalledExactlyOnceWith(container, undefined, {
+ renderer: "svg",
+ });
+
+ expect(observe).toHaveBeenCalledExactlyOnceWith(container);
+
+ expect(chart.setOption).toHaveBeenCalledExactlyOnceWith(INITIAL_OPTIONS, {
+ notMerge: true,
+ });
+
+ rerender();
+
+ expect(initChart).toHaveBeenCalledTimes(1);
+ expect(chart.setOption).toHaveBeenCalledTimes(2);
+ expect(chart.setOption).toHaveBeenLastCalledWith(UPDATED_OPTIONS, {
+ notMerge: true,
+ });
+
+ rerender();
+
+ expect(chart.dispose).toHaveBeenCalledTimes(1);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+
+ const replacement = createChart();
+ initChart.mockReturnValue(replacement);
+
+ rerender();
+
+ expect(initChart).toHaveBeenCalledTimes(2);
+ expect(replacement.setOption).toHaveBeenCalledExactlyOnceWith(
+ UPDATED_OPTIONS,
+ { notMerge: true },
+ );
+
+ unmount();
+
+ expect(replacement.dispose).toHaveBeenCalledTimes(1);
+ expect(chart.dispose).toHaveBeenCalledTimes(1);
+ expect(disconnect).toHaveBeenCalledTimes(2);
+});
+
+it("batches resize events and cancels pending work on unmount", () => {
+ vi.useFakeTimers();
+
+ const cancel = vi.spyOn(globalThis, "cancelAnimationFrame");
+ const { chart, disconnect, notifyResize } = setup();
+
+ const { unmount } = render();
+
+ notifyResize();
+ notifyResize();
+
+ expect(cancel).toHaveBeenCalledTimes(1);
+ expect(chart.resize).not.toHaveBeenCalled();
+
+ vi.advanceTimersToNextFrame();
+
+ expect(chart.resize).toHaveBeenCalledTimes(1);
+
+ // Disposed charts must not be resized.
+ chart.isDisposed.mockReturnValue(true);
+
+ notifyResize();
+ vi.advanceTimersToNextFrame();
+
+ expect(chart.resize).toHaveBeenCalledTimes(1);
+
+ // Pending resize work must be cancelled during cleanup.
+ chart.isDisposed.mockReturnValue(false);
+
+ notifyResize();
+ unmount();
+
+ expect(cancel).toHaveBeenCalledTimes(2);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ expect(chart.dispose).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(32);
+
+ expect(chart.resize).toHaveBeenCalledTimes(1);
+});
diff --git a/frontend/src/hooks/useIsMobile.test.ts b/frontend/src/hooks/useIsMobile.test.ts
new file mode 100644
index 0000000..b9c3507
--- /dev/null
+++ b/frontend/src/hooks/useIsMobile.test.ts
@@ -0,0 +1,78 @@
+// @vitest-environment jsdom
+
+import { act, renderHook } from "@testing-library/react";
+import { createElement } from "react";
+import { renderToString } from "react-dom/server";
+import { expect, it, vi } from "vitest";
+
+import { useIsMobile } from "./useIsMobile";
+
+const MOBILE_QUERY = "(max-width: 639px)";
+
+function setup(initialMatches = false) {
+ const media = Object.assign(new EventTarget(), {
+ matches: initialMatches,
+ media: MOBILE_QUERY,
+ });
+
+ const addListener = vi.spyOn(media, "addEventListener");
+ const removeListener = vi.spyOn(media, "removeEventListener");
+
+ const matchMedia = vi.fn<(query: string) => typeof media>(() => media);
+
+ vi.stubGlobal("matchMedia", matchMedia);
+
+ return {
+ matchMedia,
+ addListener,
+ removeListener,
+ setMatches: (matches: boolean) => {
+ media.matches = matches;
+ media.dispatchEvent(new Event("change"));
+ },
+ };
+}
+
+function MobileProbe() {
+ return useIsMobile() ? "mobile" : "desktop";
+}
+
+it.each([false, true])(
+ "returns the initial media query state: %s",
+ (matches) => {
+ const { matchMedia } = setup(matches);
+ const { result } = renderHook(useIsMobile);
+
+ expect(result.current).toBe(matches);
+ expect(matchMedia).toHaveBeenCalledWith(MOBILE_QUERY);
+ },
+);
+
+it("responds to media query changes and removes its subscription", () => {
+ const { addListener, removeListener, setMatches } = setup();
+ const { result, unmount } = renderHook(useIsMobile);
+
+ expect(addListener).toHaveBeenCalledExactlyOnceWith(
+ "change",
+ expect.any(Function),
+ );
+
+ const listener = addListener.mock.calls[0][1];
+
+ act(() => setMatches(true));
+ expect(result.current).toBe(true);
+
+ act(() => setMatches(false));
+ expect(result.current).toBe(false);
+
+ unmount();
+
+ expect(removeListener).toHaveBeenCalledExactlyOnceWith("change", listener);
+});
+
+it("uses the desktop fallback during server-side rendering", () => {
+ const { matchMedia } = setup(true);
+
+ expect(renderToString(createElement(MobileProbe))).toContain("desktop");
+ expect(matchMedia).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/lib/analytics.test.ts b/frontend/src/lib/analytics.test.ts
new file mode 100644
index 0000000..cf248dc
--- /dev/null
+++ b/frontend/src/lib/analytics.test.ts
@@ -0,0 +1,278 @@
+// @vitest-environment jsdom
+
+import { afterEach, expect, it, vi } from "vitest";
+
+const MEASUREMENT_ID = "G-RWW9930KEG";
+const DISABLE_KEY = `ga-disable-${MEASUREMENT_ID}`;
+
+const DENIED_CONSENT = {
+ analytics_storage: "denied",
+ ad_storage: "denied",
+ ad_user_data: "denied",
+ ad_personalization: "denied",
+};
+
+const GRANTED_CONSENT = {
+ ...DENIED_CONSENT,
+ analytics_storage: "granted",
+};
+
+async function setup() {
+ vi.resetModules();
+
+ vi.stubGlobal("dataLayer", undefined);
+ vi.stubGlobal("gtag", undefined);
+ vi.stubGlobal(DISABLE_KEY, undefined);
+
+ const appendScript = vi
+ .spyOn(document.head, "appendChild")
+ .mockImplementation((node) => node);
+
+ const analytics = await import("./analytics");
+
+ return { analytics, appendScript };
+}
+
+afterEach(() => {
+ window.localStorage.clear();
+ window.history.replaceState(null, "", "/");
+
+ for (const name of ["pdv_ga", "pdv_ga_session", "_ga", "session"]) {
+ document.cookie = `${name}=; Max-Age=0; Path=/`;
+ }
+});
+
+it("parses valid consent choices and rejects unknown values", async () => {
+ const { analytics } = await setup();
+
+ expect(
+ ["granted", "denied", null, "", "invalid", "GRANTED"].map((value) =>
+ analytics.parseStoredConsent(value),
+ ),
+ ).toEqual(["granted", "denied", null, null, null, null]);
+});
+
+it("persists and retrieves analytics consent", async () => {
+ const { analytics } = await setup();
+
+ expect(analytics.readAnalyticsConsent()).toBeNull();
+
+ analytics.saveAnalyticsConsent("granted");
+
+ expect(analytics.readAnalyticsConsent()).toBe("granted");
+
+ expect(window.localStorage.getItem(analytics.CONSENT_STORAGE_KEY)).toBe(
+ "granted",
+ );
+
+ analytics.saveAnalyticsConsent("denied");
+
+ expect(analytics.readAnalyticsConsent()).toBe("denied");
+
+ window.localStorage.setItem(analytics.CONSENT_STORAGE_KEY, "invalid");
+
+ expect(analytics.readAnalyticsConsent()).toBeNull();
+});
+
+it("handles unavailable browser storage", async () => {
+ const { analytics } = await setup();
+
+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
+ throw new Error("Storage unavailable");
+ });
+
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new Error("Storage unavailable");
+ });
+
+ expect(analytics.readAnalyticsConsent()).toBeNull();
+
+ expect(() => analytics.saveAnalyticsConsent("granted")).not.toThrow();
+});
+
+it("does not track page views before analytics initialization", async () => {
+ const { analytics, appendScript } = await setup();
+
+ analytics.trackPageView("/cohorts");
+
+ expect(window.dataLayer).toBeUndefined();
+ expect(window.gtag).toBeUndefined();
+ expect(appendScript).not.toHaveBeenCalled();
+});
+
+it("initializes analytics with privacy-preserving configuration", async () => {
+ const { analytics, appendScript } = await setup();
+
+ window.history.replaceState(
+ null,
+ "",
+ "/viewer/?private=value#/plot-longitudinal?cohort=Study+A&variables=Age",
+ );
+
+ vi.spyOn(document, "referrer", "get").mockReturnValue(
+ "https://example.test/research?private=value#details",
+ );
+
+ analytics.enableAnalytics("/plot-longitudinal");
+
+ expect(window).toHaveProperty(DISABLE_KEY, false);
+
+ expect(window.dataLayer).toEqual([
+ ["consent", "default", DENIED_CONSENT],
+ ["consent", "update", GRANTED_CONSENT],
+ ["js", expect.any(Date)],
+ [
+ "config",
+ MEASUREMENT_ID,
+ {
+ send_page_view: false,
+ cookie_prefix: "pdv",
+ cookie_domain: "none",
+ cookie_expires: 30 * 24 * 60 * 60,
+ allow_google_signals: false,
+ allow_ad_personalization_signals: false,
+ page_location: `${window.location.origin}/viewer/#/plot-longitudinal`,
+ page_title: "Variable-specific Follow-up | PDataViewer",
+ page_referrer: "https://example.test",
+ },
+ ],
+ ]);
+
+ expect(appendScript).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ id: "pdataviewer-ga4",
+ async: true,
+ src: `https://www.googletagmanager.com/gtag/js?id=${MEASUREMENT_ID}`,
+ }),
+ );
+
+ expect(document.getElementById("pdataviewer-ga4")).not.toBeInTheDocument();
+});
+
+it("initializes only once and preserves existing data layer entries", async () => {
+ const { analytics, appendScript } = await setup();
+
+ window.dataLayer = [["existing"]];
+
+ analytics.enableAnalytics("/");
+ analytics.enableAnalytics("/cohorts");
+
+ expect(appendScript).toHaveBeenCalledTimes(1);
+ expect(window.dataLayer).toHaveLength(5);
+ expect(window.dataLayer[0]).toEqual(["existing"]);
+});
+
+it.each(["", "invalid-referrer"])(
+ "omits unavailable or invalid referrers: %s",
+ async (referrer) => {
+ const { analytics } = await setup();
+
+ vi.spyOn(document, "referrer", "get").mockReturnValue(referrer);
+
+ analytics.enableAnalytics("/");
+
+ expect(window.dataLayer).toContainEqual([
+ "config",
+ MEASUREMENT_ID,
+ expect.objectContaining({
+ page_referrer: "",
+ }),
+ ]);
+ },
+);
+
+it("tracks application routes without including research parameters", async () => {
+ const { analytics } = await setup();
+
+ window.history.replaceState(
+ null,
+ "",
+ "/viewer/?private=value#/plot-longitudinal?cohort=Study+A&variables=Age",
+ );
+
+ analytics.enableAnalytics("/");
+
+ const pages = [
+ { pathname: "/", title: "Home" },
+ { pathname: "/cohorts", title: "Cohorts" },
+ { pathname: "/biomarkers", title: "Biomarkers" },
+ { pathname: "/study-picker", title: "Study Picker" },
+ { pathname: "/mappings", title: "Mappings" },
+ { pathname: "/longitudinal", title: "Longitudinal" },
+ {
+ pathname: "/plot-longitudinal",
+ title: "Variable-specific Follow-up",
+ },
+ { pathname: "/contact-us", title: "Contact Us" },
+ { pathname: "/races", title: "Race Distribution" },
+ { pathname: "/unknown", title: "PDataViewer" },
+ ];
+
+ for (const { pathname, title } of pages) {
+ analytics.trackPageView(pathname);
+
+ const page_location = `${window.location.origin}/viewer/#${pathname}`;
+
+ const page_title = `${title} | PDataViewer`;
+
+ expect(window.dataLayer?.slice(-2)).toEqual([
+ [
+ "config",
+ MEASUREMENT_ID,
+ {
+ update: true,
+ page_location,
+ page_title,
+ },
+ ],
+ [
+ "event",
+ "page_view",
+ {
+ send_to: MEASUREMENT_ID,
+ page_title,
+ page_location,
+ },
+ ],
+ ]);
+ }
+});
+
+it("disables analytics and removes only PDataViewer analytics cookies", async () => {
+ const { analytics } = await setup();
+
+ analytics.enableAnalytics("/");
+
+ document.cookie = "pdv_ga=analytics; Path=/";
+ document.cookie = "pdv_ga_session=analytics-session; Path=/";
+ document.cookie = "_ga=other-analytics; Path=/";
+ document.cookie = "session=application-session; Path=/";
+
+ analytics.disableAnalytics();
+
+ expect(window).toHaveProperty(DISABLE_KEY, true);
+
+ expect(window.dataLayer?.at(-1)).toEqual([
+ "consent",
+ "update",
+ DENIED_CONSENT,
+ ]);
+
+ const cookies = document.cookie.split("; ");
+
+ expect(cookies).not.toContain("pdv_ga=analytics");
+ expect(cookies).not.toContain("pdv_ga_session=analytics-session");
+
+ expect(cookies).toContain("_ga=other-analytics");
+ expect(cookies).toContain("session=application-session");
+});
+
+it("supports disabling analytics before initialization", async () => {
+ const { analytics, appendScript } = await setup();
+
+ analytics.disableAnalytics();
+
+ expect(window).toHaveProperty(DISABLE_KEY, true);
+ expect(window.dataLayer).toBeUndefined();
+ expect(appendScript).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/lib/analytics.ts b/frontend/src/lib/analytics.ts
index 55424bf..5a7a484 100644
--- a/frontend/src/lib/analytics.ts
+++ b/frontend/src/lib/analytics.ts
@@ -72,6 +72,7 @@ function getPageTitle(pathname: string): string {
"/longitudinal": "Longitudinal",
"/plot-longitudinal": "Variable-specific Follow-up",
"/contact-us": "Contact Us",
+ "/races": "Race Distribution",
};
return `${titles[pathname] ?? "PDataViewer"} | PDataViewer`;
@@ -202,3 +203,11 @@ export function disableAnalytics(): void {
deleteAnalyticsCookies();
}
+
+/**
+ * Reload the application after analytics consent is withdrawn
+ * to unload the previously initialized tracking script.
+ */
+export function reloadAfterAnalyticsWithdrawal(): void {
+ window.location.reload();
+}
diff --git a/frontend/src/lib/api/cdm.test.ts b/frontend/src/lib/api/cdm.test.ts
new file mode 100644
index 0000000..1661dea
--- /dev/null
+++ b/frontend/src/lib/api/cdm.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { TEST_API_URL } from "@/test/mocks/handlers";
+
+import { fetchModalities, fetchVariables } from "./cdm";
+
+describe.each([
+ {
+ fetchData: fetchVariables,
+ path: "/cdm/variables",
+ expected: ["Age", "Motor score"],
+ },
+ {
+ fetchData: fetchModalities,
+ path: "/cdm/modalities",
+ expected: ["Clinical", "Demographics"],
+ },
+])("$path", ({ fetchData, path, expected }) => {
+ it("retrieves data and forwards the abort signal", async () => {
+ const controller = new AbortController();
+ const fetch = vi.spyOn(globalThis, "fetch");
+
+ await expect(fetchData(controller.signal)).resolves.toEqual(expected);
+
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(
+ `${TEST_API_URL}${path}`,
+ expect.objectContaining({
+ method: "GET",
+ signal: controller.signal,
+ }),
+ );
+ });
+});
diff --git a/frontend/src/lib/api/client.test.ts b/frontend/src/lib/api/client.test.ts
new file mode 100644
index 0000000..7a0140d
--- /dev/null
+++ b/frontend/src/lib/api/client.test.ts
@@ -0,0 +1,435 @@
+import { http, HttpResponse } from "msw";
+import { describe, expect, it, vi } from "vitest";
+
+import { TEST_API_URL } from "@/test/mocks/handlers";
+import { server } from "@/test/mocks/server";
+
+import { api, ApiError } from "./client";
+
+const TEST_PATH = "/test-client";
+const TEST_URL = `${TEST_API_URL}${TEST_PATH}`;
+
+describe("api.get", () => {
+ it.each(["test-client", "/test-client", "///test-client"])(
+ "normalizes the request path: %s",
+ async (path) => {
+ server.use(
+ http.get(TEST_URL, ({ request }) => {
+ return HttpResponse.json({
+ method: request.method,
+ url: request.url,
+ accept: request.headers.get("Accept"),
+ });
+ }),
+ );
+
+ await expect(api.get(path)).resolves.toEqual({
+ method: "GET",
+ url: TEST_URL,
+ accept: "application/json",
+ });
+ },
+ );
+
+ it("preserves query parameters", async () => {
+ server.use(
+ http.get(TEST_URL, ({ request }) => {
+ const params = new URL(request.url).searchParams;
+
+ return HttpResponse.json({
+ cohort: params.get("cohort"),
+ variables: params.getAll("variables"),
+ });
+ }),
+ );
+
+ const params = new URLSearchParams();
+
+ params.set("cohort", "Study A & B");
+ params.append("variables", "Age");
+ params.append("variables", "Motor score");
+
+ await expect(api.get(`${TEST_PATH}?${params}`)).resolves.toEqual({
+ cohort: "Study A & B",
+ variables: ["Age", "Motor score"],
+ });
+ });
+
+ it("preserves custom request headers", async () => {
+ server.use(
+ http.get(TEST_URL, ({ request }) => {
+ return HttpResponse.json({
+ accept: request.headers.get("Accept"),
+ authorization: request.headers.get("Authorization"),
+ custom: request.headers.get("X-Test-Header"),
+ });
+ }),
+ );
+
+ await expect(
+ api.get(TEST_PATH, {
+ headers: {
+ accept: "application/vnd.example+json",
+ Authorization: "Bearer synthetic-token",
+ "X-Test-Header": "test-value",
+ },
+ }),
+ ).resolves.toEqual({
+ accept: "application/vnd.example+json",
+ authorization: "Bearer synthetic-token",
+ custom: "test-value",
+ });
+ });
+
+ it("does not mutate supplied headers", async () => {
+ const headers = new Headers({
+ "X-Test-Header": "test-value",
+ });
+
+ server.use(
+ http.get(TEST_URL, ({ request }) => {
+ return HttpResponse.json({
+ accept: request.headers.get("Accept"),
+ custom: request.headers.get("X-Test-Header"),
+ });
+ }),
+ );
+
+ await expect(api.get(TEST_PATH, { headers })).resolves.toEqual({
+ accept: "application/json",
+ custom: "test-value",
+ });
+
+ expect(headers.has("Accept")).toBe(false);
+ expect(headers.get("X-Test-Header")).toBe("test-value");
+ });
+});
+
+describe("api.post", () => {
+ it.each([
+ { body: ["Age", "Motor score"] },
+ { body: { cohort: "Study A", variables: ["Age"] } },
+ { body: null },
+ ])("serializes the JSON request body: $body", async ({ body }) => {
+ server.use(
+ http.post(TEST_URL, async ({ request }) => {
+ const payload: unknown = await request.json();
+
+ return HttpResponse.json({
+ method: request.method,
+ contentType: request.headers.get("Content-Type"),
+ accept: request.headers.get("Accept"),
+ body: payload,
+ });
+ }),
+ );
+
+ await expect(api.post(TEST_PATH, body)).resolves.toEqual({
+ method: "POST",
+ contentType: "application/json",
+ accept: "application/json",
+ body,
+ });
+ });
+
+ it("preserves custom headers while enforcing JSON content type", async () => {
+ const headers = new Headers({
+ "Content-Type": "text/plain",
+ Accept: "application/vnd.example+json",
+ Authorization: "Bearer synthetic-token",
+ });
+
+ server.use(
+ http.post(TEST_URL, ({ request }) => {
+ return HttpResponse.json({
+ contentType: request.headers.get("Content-Type"),
+ accept: request.headers.get("Accept"),
+ authorization: request.headers.get("Authorization"),
+ });
+ }),
+ );
+
+ await expect(api.post(TEST_PATH, ["Age"], { headers })).resolves.toEqual({
+ contentType: "application/json",
+ accept: "application/vnd.example+json",
+ authorization: "Bearer synthetic-token",
+ });
+
+ expect(headers.get("Content-Type")).toBe("text/plain");
+ });
+});
+
+describe("API error handling", () => {
+ it.each([
+ {
+ status: 400,
+ body: { detail: " Invalid request " },
+ message: "Invalid request",
+ },
+ {
+ status: 401,
+ body: { detail: "Could not validate credentials" },
+ message: "Could not validate credentials",
+ },
+ {
+ status: 422,
+ body: {
+ detail: [
+ { msg: " First validation error " },
+ { msg: "Second validation error" },
+ ],
+ },
+ message: "First validation error; Second validation error",
+ },
+ {
+ status: 422,
+ body: {
+ detail: [
+ null,
+ "invalid",
+ {},
+ { msg: 42 },
+ { msg: "" },
+ { msg: " " },
+ { msg: "Valid validation error" },
+ ],
+ },
+ message: "Valid validation error",
+ },
+ {
+ status: 503,
+ body: { message: " Service unavailable " },
+ message: "Service unavailable",
+ },
+ {
+ status: 400,
+ body: {
+ detail: "Preferred detail",
+ message: "Secondary message",
+ },
+ message: "Preferred detail",
+ },
+ {
+ status: 400,
+ body: {
+ detail: " ",
+ message: "Fallback message",
+ },
+ message: "Fallback message",
+ },
+ {
+ status: 422,
+ body: {
+ detail: [{ msg: " " }, {}],
+ message: "Validation failed",
+ },
+ message: "Validation failed",
+ },
+ {
+ status: 500,
+ body: { detail: 42 },
+ message: "Request failed (HTTP 500)",
+ },
+ {
+ status: 500,
+ body: { message: 42 },
+ message: "Request failed (HTTP 500)",
+ },
+ {
+ status: 500,
+ body: { message: " " },
+ message: "Request failed (HTTP 500)",
+ },
+ {
+ status: 500,
+ body: {},
+ message: "Request failed (HTTP 500)",
+ },
+ {
+ status: 500,
+ body: null,
+ message: "Request failed (HTTP 500)",
+ },
+ {
+ status: 500,
+ body: "Internal server error",
+ message: "Request failed (HTTP 500)",
+ },
+ ])(
+ "extracts the error message for HTTP $status: $message",
+ async ({ status, body, message }) => {
+ server.use(
+ http.get(TEST_URL, () => {
+ return HttpResponse.json(body, { status });
+ }),
+ );
+
+ const request = api.get(TEST_PATH);
+
+ await expect(request).rejects.toBeInstanceOf(ApiError);
+
+ await expect(request).rejects.toMatchObject({
+ name: "ApiError",
+ status,
+ message,
+ });
+ },
+ );
+
+ it("handles non-JSON error responses", async () => {
+ server.use(
+ http.get(TEST_URL, () => {
+ return HttpResponse.text("Bad Gateway", {
+ status: 502,
+ });
+ }),
+ );
+
+ await expect(api.get(TEST_PATH)).rejects.toMatchObject({
+ name: "ApiError",
+ status: 502,
+ message: "Request failed (HTTP 502)",
+ });
+ });
+
+ it("handles POST error responses", async () => {
+ server.use(
+ http.post(TEST_URL, () => {
+ return HttpResponse.json(
+ { detail: "Invalid variable selection" },
+ { status: 422 },
+ );
+ }),
+ );
+
+ await expect(
+ api.post(TEST_PATH, ["Unknown variable"]),
+ ).rejects.toMatchObject({
+ name: "ApiError",
+ status: 422,
+ message: "Invalid variable selection",
+ });
+ });
+
+ it("rejects HTTP 204 responses when JSON is expected", async () => {
+ server.use(
+ http.get(TEST_URL, () => {
+ return new HttpResponse(null, { status: 204 });
+ }),
+ );
+
+ await expect(api.get(TEST_PATH)).rejects.toThrow(
+ "Expected a JSON response, but the server returned HTTP 204.",
+ );
+ });
+
+ it("propagates JSON parsing errors from successful responses", async () => {
+ server.use(
+ http.get(TEST_URL, () => {
+ return HttpResponse.text("Invalid JSON", {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }),
+ );
+
+ await expect(api.get(TEST_PATH)).rejects.toBeInstanceOf(SyntaxError);
+ });
+
+ it("propagates network failures", async () => {
+ server.use(http.get(TEST_URL, () => HttpResponse.error()));
+
+ await expect(api.get(TEST_PATH)).rejects.toBeInstanceOf(TypeError);
+ });
+});
+
+describe("request cancellation", () => {
+ it("forwards the abort signal for GET requests", async () => {
+ const controller = new AbortController();
+ const fetch = vi.spyOn(globalThis, "fetch");
+
+ server.use(http.get(TEST_URL, () => HttpResponse.json(["Age"])));
+
+ await expect(
+ api.get(TEST_PATH, { signal: controller.signal }),
+ ).resolves.toEqual(["Age"]);
+
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(
+ TEST_URL,
+ expect.objectContaining({
+ method: "GET",
+ signal: controller.signal,
+ }),
+ );
+ });
+
+ it("forwards the abort signal for POST requests", async () => {
+ const controller = new AbortController();
+ const fetch = vi.spyOn(globalThis, "fetch");
+
+ server.use(http.post(TEST_URL, () => HttpResponse.json([])));
+
+ await expect(
+ api.post(TEST_PATH, ["Age"], {
+ signal: controller.signal,
+ }),
+ ).resolves.toEqual([]);
+
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(
+ TEST_URL,
+ expect.objectContaining({
+ method: "POST",
+ signal: controller.signal,
+ }),
+ );
+ });
+
+ it("rejects requests with an already aborted signal", async () => {
+ const controller = new AbortController();
+
+ controller.abort();
+
+ server.use(http.get(TEST_URL, () => HttpResponse.json(["Age"])));
+
+ await expect(
+ api.get(TEST_PATH, { signal: controller.signal }),
+ ).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ });
+});
+
+describe("API configuration", () => {
+ it("removes trailing slashes from the API base URL", async () => {
+ vi.resetModules();
+ vi.stubEnv("VITE_API_URL", `${TEST_API_URL}///`);
+
+ const { api: configuredApi } = await import("./client");
+
+ server.use(
+ http.get(TEST_URL, ({ request }) => {
+ return HttpResponse.json({
+ url: request.url,
+ });
+ }),
+ );
+
+ await expect(configuredApi.get("///test-client")).resolves.toEqual({
+ url: TEST_URL,
+ });
+ });
+
+ it.each([{ value: undefined }, { value: "" }, { value: "///" }])(
+ "rejects missing API configuration: $value",
+ async ({ value }) => {
+ vi.resetModules();
+ vi.stubEnv("VITE_API_URL", value);
+
+ await expect(import("./client")).rejects.toThrow(
+ "VITE_API_URL is not configured",
+ );
+ },
+ );
+});
diff --git a/frontend/src/lib/api/cohorts.test.ts b/frontend/src/lib/api/cohorts.test.ts
new file mode 100644
index 0000000..3fc1711
--- /dev/null
+++ b/frontend/src/lib/api/cohorts.test.ts
@@ -0,0 +1,51 @@
+import { http, HttpResponse } from "msw";
+import { expect, it, vi } from "vitest";
+
+import { mockCohorts, mockMetadata, TEST_API_URL } from "@/test/mocks/handlers";
+import { server } from "@/test/mocks/server";
+
+import { fetchCohorts, fetchMetadata, type Metadata } from "./cohorts";
+
+const metadata = {
+ ...mockMetadata,
+ "Study B": {
+ ...mockMetadata["Study B"],
+ participants: null,
+ controlParticipants: 0,
+ longitudinalParticipants: null,
+ longitudinalDataAvailable: true,
+ },
+} satisfies Metadata;
+
+it.each([
+ {
+ fetchData: fetchCohorts,
+ path: "/cohorts/",
+ expected: mockCohorts,
+ },
+ {
+ fetchData: fetchMetadata,
+ path: "/cohorts/metadata",
+ expected: metadata,
+ },
+])(
+ "retrieves $path and forwards the abort signal",
+ async ({ fetchData, path, expected }) => {
+ const controller = new AbortController();
+ const fetch = vi.spyOn(globalThis, "fetch");
+
+ server.use(
+ http.get(`${TEST_API_URL}${path}`, () => HttpResponse.json(expected)),
+ );
+
+ await expect(fetchData(controller.signal)).resolves.toEqual(expected);
+
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(
+ `${TEST_API_URL}${path}`,
+ expect.objectContaining({
+ method: "GET",
+ signal: controller.signal,
+ }),
+ );
+ },
+);
diff --git a/frontend/src/lib/charts/download-svg.test.ts b/frontend/src/lib/charts/download-svg.test.ts
new file mode 100644
index 0000000..f597415
--- /dev/null
+++ b/frontend/src/lib/charts/download-svg.test.ts
@@ -0,0 +1,156 @@
+// @vitest-environment jsdom
+
+import { describe, expect, it, vi } from "vitest";
+
+import { downloadChartSvg } from "./download-svg";
+
+const SVG_DATA_URL = "data:image/svg+xml;charset=UTF-8,%3Csvg%3E%3C%2Fsvg%3E";
+
+type ExportChart = NonNullable[0]>;
+
+function createMockChart(disposed = false) {
+ return {
+ isDisposed: vi.fn(() => disposed),
+ getDataURL: vi.fn(() => SVG_DATA_URL),
+ };
+}
+
+function captureDownloads() {
+ const downloads: {
+ anchor: HTMLAnchorElement;
+ attached: boolean;
+ }[] = [];
+
+ const click = vi
+ .spyOn(HTMLAnchorElement.prototype, "click")
+ .mockImplementation(function (this: HTMLAnchorElement) {
+ downloads.push({
+ anchor: this,
+ attached: document.body.contains(this),
+ });
+ });
+
+ return { click, downloads };
+}
+
+describe("downloadChartSvg", () => {
+ it("exports the chart as an SVG with a white background", () => {
+ const chart = createMockChart();
+ const { click, downloads } = captureDownloads();
+
+ downloadChartSvg(chart, "Biomarker distributions");
+
+ expect(chart.isDisposed).toHaveBeenCalledTimes(1);
+
+ expect(chart.getDataURL).toHaveBeenCalledExactlyOnceWith({
+ type: "svg",
+ backgroundColor: "#ffffff",
+ });
+
+ expect(click).toHaveBeenCalledTimes(1);
+ expect(downloads).toHaveLength(1);
+
+ const { anchor, attached } = downloads[0];
+
+ expect(anchor).toHaveAttribute("href", SVG_DATA_URL);
+
+ expect(anchor).toHaveAttribute("download", "biomarker-distributions.svg");
+
+ expect(attached).toBe(true);
+ expect(anchor).not.toBeInTheDocument();
+ });
+
+ it.each([
+ {
+ title: "Participant Retention",
+ filename: "participant-retention.svg",
+ },
+ {
+ title: " UPDRS III / Total Score ",
+ filename: "updrs-iii-total-score.svg",
+ },
+ {
+ title: "Age___at---baseline",
+ filename: "age-at-baseline.svg",
+ },
+ {
+ title: "Age 12",
+ filename: "age-12.svg",
+ },
+ {
+ title: "MÜNCHEN 研究 42",
+ filename: "münchen-研究-42.svg",
+ },
+ {
+ title: "../../Study A\\Age",
+ filename: "study-a-age.svg",
+ },
+ {
+ title: "",
+ filename: "chart.svg",
+ },
+ {
+ title: " ",
+ filename: "chart.svg",
+ },
+ {
+ title: "!@#$%^&*()",
+ filename: "chart.svg",
+ },
+ {
+ title: "a".repeat(150),
+ filename: `${"a".repeat(100)}.svg`,
+ },
+ {
+ title: `${"a".repeat(99)} - b`,
+ filename: `${"a".repeat(99)}.svg`,
+ },
+ ])("normalizes the filename: $title", ({ title, filename }) => {
+ const chart = createMockChart();
+ const { click, downloads } = captureDownloads();
+
+ downloadChartSvg(chart, title);
+
+ expect(click).toHaveBeenCalledTimes(1);
+ expect(downloads).toHaveLength(1);
+
+ const { anchor } = downloads[0];
+
+ expect(anchor).toHaveAttribute("download", filename);
+ expect(anchor).not.toBeInTheDocument();
+ });
+
+ it("does not initiate a download when the chart is null", () => {
+ const { click, downloads } = captureDownloads();
+
+ downloadChartSvg(null, "Missing chart");
+
+ expect(click).not.toHaveBeenCalled();
+ expect(downloads).toEqual([]);
+ });
+
+ it("does not export a disposed chart", () => {
+ const chart = createMockChart(true);
+ const { click, downloads } = captureDownloads();
+
+ downloadChartSvg(chart, "Disposed chart");
+
+ expect(chart.isDisposed).toHaveBeenCalledTimes(1);
+ expect(chart.getDataURL).not.toHaveBeenCalled();
+ expect(click).not.toHaveBeenCalled();
+ expect(downloads).toEqual([]);
+ });
+
+ it("propagates chart export errors without initiating a download", () => {
+ const chart = createMockChart();
+ const { click } = captureDownloads();
+
+ chart.getDataURL.mockImplementation(() => {
+ throw new Error("SVG export failed");
+ });
+
+ expect(() => downloadChartSvg(chart, "Age")).toThrow("SVG export failed");
+
+ expect(click).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/lib/charts/download-svg.ts b/frontend/src/lib/charts/download-svg.ts
index 802ca0d..c782d8e 100644
--- a/frontend/src/lib/charts/download-svg.ts
+++ b/frontend/src/lib/charts/download-svg.ts
@@ -1,7 +1,7 @@
import type { EChartsType } from "echarts/core";
export function downloadChartSvg(
- chart: EChartsType | null,
+ chart: Pick | null,
title: string,
): void {
if (!chart || chart.isDisposed()) return;
diff --git a/frontend/src/lib/formatters.test.ts b/frontend/src/lib/formatters.test.ts
new file mode 100644
index 0000000..af6408b
--- /dev/null
+++ b/frontend/src/lib/formatters.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+
+import { formatMeasurement, formatNumber } from "./formatters";
+
+const invalidValues = [
+ { label: "null", value: null },
+ { label: "undefined", value: undefined },
+ { label: "NaN", value: NaN },
+ { label: "positive infinity", value: Infinity },
+ { label: "negative infinity", value: -Infinity },
+];
+
+describe("formatNumber", () => {
+ it.each([
+ { value: 0, expected: "0" },
+ { value: 1234, expected: "1,234" },
+ { value: -1234, expected: "-1,234" },
+ { value: 1234567, expected: "1,234,567" },
+ { value: 12.5, expected: "12.5" },
+ { value: 1234.56789, expected: "1,234.568" },
+ ])("formats $value as $expected", ({ value, expected }) => {
+ expect(formatNumber(value)).toBe(expected);
+ });
+
+ it.each(invalidValues)("returns the fallback for $label", ({ value }) => {
+ expect(formatNumber(value)).toBe("N/R");
+ expect(formatNumber(value, "Unavailable")).toBe("Unavailable");
+ });
+
+ it("does not use the fallback for finite values", () => {
+ expect(formatNumber(0, "Unavailable")).toBe("0");
+ expect(formatNumber(42, "Unavailable")).toBe("42");
+ });
+
+ it("supports an empty fallback", () => {
+ expect(formatNumber(null, "")).toBe("");
+ });
+});
+
+describe("formatMeasurement", () => {
+ it.each([
+ { value: 0, expected: "0" },
+ { value: 12.5, expected: "12.5" },
+ { value: 1.234567, expected: "1.2346" },
+ { value: 12345.678, expected: "12,346" },
+ { value: -1234.567, expected: "-1,234.6" },
+ { value: 0.000123456, expected: "0.00012346" },
+ ])("formats $value as $expected", ({ value, expected }) => {
+ expect(formatMeasurement(value)).toBe(expected);
+ });
+
+ it.each(invalidValues)("returns the fallback for $label", ({ value }) => {
+ expect(formatMeasurement(value)).toBe("N/R");
+ expect(formatMeasurement(value, "Unavailable")).toBe("Unavailable");
+ });
+
+ it("does not use the fallback for finite values", () => {
+ expect(formatMeasurement(0, "Unavailable")).toBe("0");
+ expect(formatMeasurement(42, "Unavailable")).toBe("42");
+ });
+
+ it("supports an empty fallback", () => {
+ expect(formatMeasurement(undefined, "")).toBe("");
+ });
+});
diff --git a/frontend/src/lib/html.test.ts b/frontend/src/lib/html.test.ts
new file mode 100644
index 0000000..250f916
--- /dev/null
+++ b/frontend/src/lib/html.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+
+import { escapeHtml } from "./html";
+
+describe("escapeHtml", () => {
+ it.each([
+ { value: "&", expected: "&" },
+ { value: "<", expected: "<" },
+ { value: ">", expected: ">" },
+ { value: '"', expected: """ },
+ { value: "'", expected: "'" },
+ ])("escapes $value as $expected", ({ value, expected }) => {
+ expect(escapeHtml(value)).toBe(expected);
+ });
+
+ it.each([
+ "",
+ "PPMI",
+ "Study A",
+ "UPDRS III - Total Score",
+ "123.45",
+ "Parkinson’s disease",
+ "München",
+ "İstanbul",
+ "研究",
+ ])("preserves plain text: %s", (value) => {
+ expect(escapeHtml(value)).toBe(value);
+ });
+
+ it("escapes multiple special characters", () => {
+ expect(escapeHtml(`A & B < C > D "E" 'F'`)).toBe(
+ "A & B < C > D "E" 'F'",
+ );
+ });
+
+ it("escapes repeated special characters", () => {
+ expect(escapeHtml("&&<<>>")).toBe("&&<<>>");
+ });
+
+ it("escapes HTML elements", () => {
+ expect(escapeHtml("Study A")).toBe(
+ "<strong>Study A</strong>",
+ );
+ });
+
+ it("escapes script elements", () => {
+ expect(escapeHtml("")).toBe(
+ "<script>alert('test')</script>",
+ );
+ });
+
+ it("escapes HTML containing event handlers", () => {
+ expect(escapeHtml('
')).toBe(
+ "<img src="invalid" onerror="alert(1)">",
+ );
+ });
+
+ it("escapes existing HTML entities", () => {
+ expect(escapeHtml("<script>")).toBe("<script>");
+ });
+
+ it("preserves whitespace and line breaks", () => {
+ expect(escapeHtml(" Study A\nStudy B\t")).toBe(" Study A\nStudy B\t");
+ });
+});
diff --git a/frontend/src/lib/url.test.ts b/frontend/src/lib/url.test.ts
new file mode 100644
index 0000000..1484547
--- /dev/null
+++ b/frontend/src/lib/url.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+
+import { safeExternalUrl } from "./url";
+
+describe("safeExternalUrl", () => {
+ it.each([
+ {
+ value: "https://example.test",
+ expected: "https://example.test/",
+ },
+ {
+ value: "http://example.test",
+ expected: "http://example.test/",
+ },
+ {
+ value: "https://example.test/study",
+ expected: "https://example.test/study",
+ },
+ {
+ value: "https://doi.org/10.0000/example",
+ expected: "https://doi.org/10.0000/example",
+ },
+ {
+ value: "https://example.test/study?id=123#metadata",
+ expected: "https://example.test/study?id=123#metadata",
+ },
+ {
+ value: "https://example.test:8443/study",
+ expected: "https://example.test:8443/study",
+ },
+ ])("accepts valid HTTP(S) URL: $value", ({ value, expected }) => {
+ expect(safeExternalUrl(value)).toBe(expected);
+ });
+
+ it.each([
+ {
+ value: "HTTPS://EXAMPLE.TEST",
+ expected: "https://example.test/",
+ },
+ {
+ value: " https://example.test/study ",
+ expected: "https://example.test/study",
+ },
+ {
+ value: "https://example.test/Study A",
+ expected: "https://example.test/Study%20A",
+ },
+ {
+ value: "https://example.test:443/study",
+ expected: "https://example.test/study",
+ },
+ {
+ value: "http://example.test:80/study",
+ expected: "http://example.test/study",
+ },
+ {
+ value: "https://example.test/a/../study",
+ expected: "https://example.test/study",
+ },
+ ])("normalizes $value", ({ value, expected }) => {
+ expect(safeExternalUrl(value)).toBe(expected);
+ });
+
+ it.each([null, "", " ", "\t\n"])(
+ "rejects missing or blank URLs: %s",
+ (value) => {
+ expect(safeExternalUrl(value)).toBeNull();
+ },
+ );
+
+ it.each([
+ "example.test",
+ "not a URL",
+ "https://",
+ "http://",
+ "https://invalid host.test",
+ "https://example.test:invalid",
+ "https://example.test:99999",
+ "https://[invalid]",
+ ])("rejects malformed or incomplete URLs: %s", (value) => {
+ expect(safeExternalUrl(value)).toBeNull();
+ });
+
+ it.each([
+ "/cohorts",
+ "./study",
+ "../study",
+ "//example.test/study",
+ "#metadata",
+ "?id=123",
+ ])("rejects relative URLs: %s", (value) => {
+ expect(safeExternalUrl(value)).toBeNull();
+ });
+
+ it.each([
+ "javascript:alert(1)",
+ "JAVASCRIPT:alert(1)",
+ " javascript:alert(1)",
+ "java\tscript:alert(1)",
+ "data:text/html,",
+ "vbscript:msgbox(1)",
+ "file:///etc/passwd",
+ "ftp://example.test/study",
+ "mailto:test@example.test",
+ "tel:+49123456789",
+ "blob:https://example.test/resource",
+ "about:blank",
+ "ws://example.test",
+ "wss://example.test",
+ ])("rejects unsupported URL protocols: %s", (value) => {
+ expect(safeExternalUrl(value)).toBeNull();
+ });
+});
diff --git a/frontend/src/test/chart-utils.ts b/frontend/src/test/chart-utils.ts
new file mode 100644
index 0000000..3a27067
--- /dev/null
+++ b/frontend/src/test/chart-utils.ts
@@ -0,0 +1,15 @@
+export function getFormatter(option: unknown) {
+ if (
+ typeof option !== "object" ||
+ option === null ||
+ !("formatter" in option) ||
+ typeof option.formatter !== "function"
+ ) {
+ throw new Error("Expected a callable chart formatter");
+ }
+
+ const formatter = option.formatter;
+
+ return (params: unknown): unknown =>
+ Reflect.apply(formatter, undefined, [params]);
+}
diff --git a/frontend/src/test/mocks/handlers.test.ts b/frontend/src/test/mocks/handlers.test.ts
new file mode 100644
index 0000000..ae0bb38
--- /dev/null
+++ b/frontend/src/test/mocks/handlers.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+
+import { fetchBiomarkerMeasurements } from "@/features/biomarkers/api";
+import { fetchLongitudinalDataForCohort } from "@/features/longitudinal/api";
+import { fetchChordDiagram } from "@/features/mappings/api";
+import { fetchRaceDistribution } from "@/features/races/api";
+import { rankCohorts } from "@/features/study-picker/api";
+import { fetchMetadata } from "@/lib/api/cohorts";
+
+import {
+ mockChordData,
+ mockMetadata,
+ mockRaceDistribution,
+ mockRankings,
+} from "./handlers";
+
+describe("Default MSW handlers", () => {
+ it("returns cohort metadata", async () => {
+ await expect(fetchMetadata()).resolves.toEqual(mockMetadata);
+ });
+
+ it("returns filtered biomarker measurements", async () => {
+ await expect(
+ fetchBiomarkerMeasurements({
+ biomarker: "Age",
+ cohort: "Study A",
+ diagnosis: "PD",
+ }),
+ ).resolves.toEqual([65, 70, 75]);
+ });
+
+ it("returns cohort-specific longitudinal data", async () => {
+ const data = await fetchLongitudinalDataForCohort("Age", "Study B");
+
+ expect(data).toHaveLength(2);
+ expect(data.every((row) => row.cohort === "Study B")).toBe(true);
+ });
+
+ it("returns chord diagram data", async () => {
+ await expect(fetchChordDiagram("Demographics")).resolves.toEqual(
+ mockChordData,
+ );
+ });
+
+ it("returns aggregated race distributions", async () => {
+ await expect(
+ fetchRaceDistribution(["Study A", "Study B"]),
+ ).resolves.toEqual(mockRaceDistribution);
+ });
+
+ it("returns cohort rankings", async () => {
+ await expect(rankCohorts(["Age", "Motor score"])).resolves.toEqual(
+ mockRankings,
+ );
+ });
+});
diff --git a/frontend/src/test/mocks/handlers.ts b/frontend/src/test/mocks/handlers.ts
new file mode 100644
index 0000000..935e146
--- /dev/null
+++ b/frontend/src/test/mocks/handlers.ts
@@ -0,0 +1,368 @@
+import { http, HttpResponse } from "msw";
+
+import type { LongitudinalData } from "@/features/longitudinal/types";
+import type { ChordDiagramData } from "@/features/mappings/types";
+import type { RaceDistributionData } from "@/features/races/types";
+import type { RankedCohort } from "@/features/study-picker/types";
+import type { Metadata } from "@/lib/api/cohorts";
+
+export const TEST_API_URL = "http://pdataviewer.example.test/api";
+
+export const mockCohorts = ["Study A", "Study B"];
+
+export const mockMetadata = {
+ "Study A": {
+ participants: 100,
+ controlParticipants: 30,
+ prodromalParticipants: 10,
+ pdParticipants: 60,
+ longitudinalParticipants: 80,
+ longitudinalDataAvailable: true,
+ followUpInterval: "12 months",
+ location: "Germany",
+ doi: "10.0000/study-a",
+ link: "https://example.test/study-a",
+ color: "#2563eb",
+ },
+ "Study B": {
+ participants: 50,
+ controlParticipants: 20,
+ prodromalParticipants: 0,
+ pdParticipants: 30,
+ longitudinalParticipants: 40,
+ longitudinalDataAvailable: true,
+ followUpInterval: "6 months",
+ location: "United Kingdom",
+ doi: null,
+ link: null,
+ color: "#059669",
+ },
+} satisfies Metadata;
+
+export const mockVariables = ["Age", "Motor score"];
+export const mockModalities = ["Clinical", "Demographics"];
+export const mockBiomarkers = ["Age", "Motor score"];
+
+const biomarkerGroups = [
+ {
+ biomarker: "Age",
+ cohort: "Study A",
+ diagnosis: "HC",
+ values: [50, 55, 60],
+ },
+ {
+ biomarker: "Age",
+ cohort: "Study A",
+ diagnosis: "PD",
+ values: [65, 70, 75],
+ },
+ {
+ biomarker: "Age",
+ cohort: "Study B",
+ diagnosis: "PD",
+ values: [60, 65, 70],
+ },
+ {
+ biomarker: "Motor score",
+ cohort: "Study A",
+ diagnosis: "PD",
+ values: [10, 20, 30],
+ },
+];
+
+export const mockLongitudinalVariables = ["Age", "Study Visit"];
+
+export const mockLongitudinalData = [
+ {
+ months: 0,
+ cohort: "Study A",
+ patientCount: 80,
+ totalPatientCount: 100,
+ },
+ {
+ months: 12,
+ cohort: "Study A",
+ patientCount: 60,
+ totalPatientCount: 100,
+ },
+ {
+ months: 0,
+ cohort: "Study B",
+ patientCount: 40,
+ totalPatientCount: 50,
+ },
+ {
+ months: 6,
+ cohort: "Study B",
+ patientCount: 30,
+ totalPatientCount: 50,
+ },
+] satisfies LongitudinalData[];
+
+export const mockChordData = {
+ nodes: [
+ { name: "Age", group: "Study A" },
+ { name: "Enrollment age", group: "Study B" },
+ ],
+ links: [
+ {
+ source: "Age",
+ target: "Enrollment age",
+ },
+ ],
+} satisfies ChordDiagramData;
+
+export const mockRaceDistribution = [
+ {
+ name: "White",
+ value: 95,
+ validCount: 135,
+ unknownCount: 8,
+ missingCount: 7,
+ },
+ {
+ name: "Asian",
+ value: 30,
+ validCount: 135,
+ unknownCount: 8,
+ missingCount: 7,
+ },
+] satisfies RaceDistributionData[];
+
+const studyARaceDistribution = [
+ {
+ name: "White",
+ value: 60,
+ validCount: 90,
+ unknownCount: 5,
+ missingCount: 5,
+ },
+ {
+ name: "Asian",
+ value: 20,
+ validCount: 90,
+ unknownCount: 5,
+ missingCount: 5,
+ },
+] satisfies RaceDistributionData[];
+
+const studyBRaceDistribution = [
+ {
+ name: "White",
+ value: 35,
+ validCount: 45,
+ unknownCount: 3,
+ missingCount: 2,
+ },
+ {
+ name: "Asian",
+ value: 10,
+ validCount: 45,
+ unknownCount: 3,
+ missingCount: 2,
+ },
+] satisfies RaceDistributionData[];
+
+export const mockRankings = [
+ {
+ cohort: "Study A",
+ found: "2/2 (100.0%)",
+ missing: "",
+ },
+ {
+ cohort: "Study B",
+ found: "1/2 (50.0%)",
+ missing: "Motor score",
+ },
+] satisfies RankedCohort[];
+
+export const handlers = [
+ // Cohorts
+
+ http.get(`${TEST_API_URL}/cohorts/`, () => {
+ return HttpResponse.json(mockCohorts);
+ }),
+
+ http.get(`${TEST_API_URL}/cohorts/metadata`, () => {
+ return HttpResponse.json(mockMetadata);
+ }),
+
+ // Common data model
+
+ http.get(`${TEST_API_URL}/cdm/variables`, () => {
+ return HttpResponse.json(mockVariables);
+ }),
+
+ http.get(`${TEST_API_URL}/cdm/modalities`, () => {
+ return HttpResponse.json(mockModalities);
+ }),
+
+ // Biomarkers
+
+ http.get(`${TEST_API_URL}/biomarkers/`, () => {
+ return HttpResponse.json(mockBiomarkers);
+ }),
+
+ http.get(`${TEST_API_URL}/biomarkers/cohorts`, ({ request }) => {
+ const biomarker = new URL(request.url).searchParams.get("biomarker");
+
+ const cohorts = [
+ ...new Set(
+ biomarkerGroups
+ .filter((group) => group.biomarker === biomarker)
+ .map((group) => group.cohort),
+ ),
+ ];
+
+ return HttpResponse.json(cohorts);
+ }),
+
+ http.get(`${TEST_API_URL}/biomarkers/diagnoses`, ({ request }) => {
+ const biomarker = new URL(request.url).searchParams.get("biomarker");
+
+ const options = mockCohorts.flatMap((cohort) => {
+ const groups = biomarkerGroups.filter(
+ (group) => group.biomarker === biomarker && group.cohort === cohort,
+ );
+
+ const labels = groups.map(
+ (group) => `${cohort} (${group.diagnosis} Group)`,
+ );
+
+ if (groups.length > 1) {
+ labels.push(`${cohort} (Complete)`);
+ }
+
+ return labels;
+ });
+
+ return HttpResponse.json(options);
+ }),
+
+ http.get(
+ `${TEST_API_URL}/biomarkers/cohorts/:cohort/diagnoses/:diagnosis`,
+ ({ request, params }) => {
+ const biomarker = new URL(request.url).searchParams.get("biomarker");
+
+ const values = biomarkerGroups
+ .filter(
+ (group) =>
+ group.biomarker === biomarker &&
+ group.cohort === params.cohort &&
+ (params.diagnosis === "Complete" ||
+ group.diagnosis === params.diagnosis),
+ )
+ .flatMap((group) => group.values);
+
+ return HttpResponse.json(values);
+ },
+ ),
+
+ // Longitudinal
+
+ http.get(`${TEST_API_URL}/longitudinal/`, () => {
+ return HttpResponse.json(mockLongitudinalVariables);
+ }),
+
+ http.get(`${TEST_API_URL}/longitudinal/:variable`, ({ params }) => {
+ const available =
+ typeof params.variable === "string" &&
+ mockLongitudinalVariables.includes(params.variable);
+
+ return HttpResponse.json(available ? mockLongitudinalData : []);
+ }),
+
+ http.get(`${TEST_API_URL}/longitudinal/:variable/:cohort`, ({ params }) => {
+ const available =
+ typeof params.variable === "string" &&
+ mockLongitudinalVariables.includes(params.variable);
+
+ const data = available
+ ? mockLongitudinalData.filter((row) => row.cohort === params.cohort)
+ : [];
+
+ return HttpResponse.json(data);
+ }),
+
+ // Mappings
+
+ http.get(`${TEST_API_URL}/visualization/chords/`, ({ request }) => {
+ const modality = new URL(request.url).searchParams.get("modality");
+
+ return HttpResponse.json(
+ modality === "Demographics" ? mockChordData : { nodes: [], links: [] },
+ );
+ }),
+
+ // Race distribution
+
+ http.get(`${TEST_API_URL}/races/cohorts`, () => {
+ return HttpResponse.json(mockCohorts);
+ }),
+
+ http.get(`${TEST_API_URL}/races/distribution`, ({ request }) => {
+ const cohorts = new URL(request.url).searchParams.getAll("cohorts");
+
+ const includesStudyA = cohorts.includes("Study A");
+ const includesStudyB = cohorts.includes("Study B");
+
+ if (cohorts.length === 0 || (includesStudyA && includesStudyB)) {
+ return HttpResponse.json(mockRaceDistribution);
+ }
+
+ if (includesStudyA) {
+ return HttpResponse.json(studyARaceDistribution);
+ }
+
+ if (includesStudyB) {
+ return HttpResponse.json(studyBRaceDistribution);
+ }
+
+ return HttpResponse.json([]);
+ }),
+
+ // Study Picker
+
+ http.get(`${TEST_API_URL}/study-picker/variables`, () => {
+ return HttpResponse.json(mockVariables);
+ }),
+
+ http.post(`${TEST_API_URL}/study-picker/rank`, async ({ request }) => {
+ const body: unknown = await request.json();
+
+ switch (JSON.stringify(body)) {
+ case '["Age","Motor score"]':
+ case '["Motor score","Age"]':
+ return HttpResponse.json(mockRankings);
+
+ case '["Age"]':
+ return HttpResponse.json([
+ {
+ cohort: "Study A",
+ found: "1/1 (100.0%)",
+ missing: "",
+ },
+ {
+ cohort: "Study B",
+ found: "1/1 (100.0%)",
+ missing: "",
+ },
+ ] satisfies RankedCohort[]);
+
+ case '["Motor score"]':
+ return HttpResponse.json([
+ {
+ cohort: "Study A",
+ found: "1/1 (100.0%)",
+ missing: "",
+ },
+ ] satisfies RankedCohort[]);
+
+ default:
+ return HttpResponse.json(
+ { detail: "Unsupported variable selection in test fixture." },
+ { status: 422 },
+ );
+ }
+ }),
+];
diff --git a/frontend/src/test/mocks/server.test.ts b/frontend/src/test/mocks/server.test.ts
new file mode 100644
index 0000000..9d5f40c
--- /dev/null
+++ b/frontend/src/test/mocks/server.test.ts
@@ -0,0 +1,20 @@
+import { http, HttpResponse } from "msw";
+import { describe, expect, it } from "vitest";
+
+import { api } from "@/lib/api/client";
+
+import { server } from "./server";
+
+describe("MSW server", () => {
+ it("intercepts API requests", async () => {
+ server.use(
+ http.get("http://pdataviewer.example.test/api/cohorts/", () =>
+ HttpResponse.json(["Study A", "Study B"]),
+ ),
+ );
+
+ const cohorts = await api.get("/cohorts/");
+
+ expect(cohorts).toEqual(["Study A", "Study B"]);
+ });
+});
diff --git a/frontend/src/test/mocks/server.ts b/frontend/src/test/mocks/server.ts
new file mode 100644
index 0000000..fa95245
--- /dev/null
+++ b/frontend/src/test/mocks/server.ts
@@ -0,0 +1,5 @@
+import { setupServer } from "msw/node";
+
+import { handlers } from "./handlers";
+
+export const server = setupServer(...handlers);
diff --git a/frontend/src/test/render.test.tsx b/frontend/src/test/render.test.tsx
new file mode 100644
index 0000000..b962ba9
--- /dev/null
+++ b/frontend/src/test/render.test.tsx
@@ -0,0 +1,79 @@
+// @vitest-environment jsdom
+
+import { useQuery } from "@tanstack/react-query";
+import { renderHook, screen, waitFor } from "@testing-library/react";
+import { Link, useLocation } from "react-router";
+import { describe, expect, it } from "vitest";
+
+import { fetchCohorts } from "@/lib/api/cohorts";
+
+import {
+ createTestQueryClient,
+ createTestWrapper,
+ renderWithProviders,
+} from "./render";
+
+function NavigationProbe() {
+ const { pathname } = useLocation();
+
+ return (
+ <>
+
+ Cohorts
+ >
+ );
+}
+
+describe("Testing infrastructure", () => {
+ it("creates independent query clients", () => {
+ const first = createTestQueryClient();
+ const second = createTestQueryClient();
+
+ first.setQueryData(["cohorts"], ["Study A"]);
+
+ expect(first).not.toBe(second);
+
+ expect(first.getQueryData(["cohorts"])).toEqual(["Study A"]);
+
+ expect(second.getQueryData(["cohorts"])).toBeUndefined();
+
+ first.clear();
+ second.clear();
+ });
+
+ it("supports router navigation", async () => {
+ const { user } = renderWithProviders(, {
+ route: "/study-picker",
+ });
+
+ expect(screen.getByRole("status")).toHaveTextContent("/study-picker");
+
+ await user.click(screen.getByRole("link", { name: "Cohorts" }));
+
+ expect(screen.getByRole("status")).toHaveTextContent("/cohorts");
+ });
+
+ it("supports TanStack Query hooks and MSW", async () => {
+ const { wrapper, queryClient } = createTestWrapper();
+
+ const { result } = renderHook(
+ () =>
+ useQuery({
+ queryKey: ["cohorts"],
+ queryFn: ({ signal }) => fetchCohorts(signal),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(result.current.data).toEqual(["Study A", "Study B"]);
+
+ expect(queryClient.getQueryData(["cohorts"])).toEqual([
+ "Study A",
+ "Study B",
+ ]);
+ });
+});
diff --git a/frontend/src/test/render.tsx b/frontend/src/test/render.tsx
new file mode 100644
index 0000000..8ee5eee
--- /dev/null
+++ b/frontend/src/test/render.tsx
@@ -0,0 +1,78 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, type RenderOptions } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { PropsWithChildren, ReactElement } from "react";
+import { MemoryRouter } from "react-router";
+import { onTestFinished } from "vitest";
+
+interface TestProviderOptions {
+ route?: string | null;
+ queryClient?: QueryClient;
+}
+
+type TestRenderOptions = Omit & TestProviderOptions;
+
+export function createTestQueryClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ staleTime: 60_000,
+ gcTime: Infinity,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ },
+ mutations: {
+ retry: false,
+ gcTime: Infinity,
+ },
+ },
+ });
+}
+
+export function createTestWrapper({
+ route = "/",
+ queryClient = createTestQueryClient(),
+}: TestProviderOptions = {}) {
+ onTestFinished(() => {
+ queryClient.clear();
+ });
+
+ function TestProviders({ children }: PropsWithChildren) {
+ return (
+
+ {route === null ? (
+ children
+ ) : (
+ {children}
+ )}
+
+ );
+ }
+
+ return {
+ queryClient,
+ wrapper: TestProviders,
+ };
+}
+
+export function renderWithProviders(
+ ui: ReactElement,
+ { route = "/", queryClient, ...renderOptions }: TestRenderOptions = {},
+) {
+ const { wrapper, queryClient: client } = createTestWrapper({
+ route,
+ queryClient,
+ });
+
+ const user = userEvent.setup();
+
+ return {
+ ...render(ui, {
+ ...renderOptions,
+ wrapper,
+ }),
+ queryClient: client,
+ user,
+ };
+}
diff --git a/frontend/src/test/setup.test.tsx b/frontend/src/test/setup.test.tsx
new file mode 100644
index 0000000..77a6788
--- /dev/null
+++ b/frontend/src/test/setup.test.tsx
@@ -0,0 +1,18 @@
+// @vitest-environment jsdom
+
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+
+describe("Testing infrastructure", () => {
+ it("supports React rendering and DOM assertions", () => {
+ render();
+
+ const button = screen.getByRole("button", {
+ name: "Test button",
+ });
+
+ expect(button).toBeInTheDocument();
+ expect(button).toBeEnabled();
+ expect(button).toBeVisible();
+ });
+});
diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts
new file mode 100644
index 0000000..96fa687
--- /dev/null
+++ b/frontend/src/test/setup.ts
@@ -0,0 +1,34 @@
+import { afterAll, afterEach, beforeAll, vi } from "vitest";
+
+import { server } from "./mocks/server";
+
+const cleanup =
+ typeof document !== "undefined"
+ ? (await import("@testing-library/react")).cleanup
+ : undefined;
+
+if (typeof document !== "undefined") {
+ await import("@testing-library/jest-dom/vitest");
+}
+
+beforeAll(() => {
+ server.listen({
+ onUnhandledFrame: "error",
+ });
+});
+
+afterEach(() => {
+ try {
+ cleanup?.();
+ } finally {
+ server.resetHandlers();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ }
+});
+
+afterAll(() => {
+ server.close();
+});
diff --git a/frontend/tsconfig.e2e.json b/frontend/tsconfig.e2e.json
new file mode 100644
index 0000000..4329112
--- /dev/null
+++ b/frontend/tsconfig.e2e.json
@@ -0,0 +1,8 @@
+{
+ "extends": "./tsconfig.app.json",
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.e2e.tsbuildinfo",
+ "types": ["node", "vite/client"]
+ },
+ "include": ["playwright.config.ts", "e2e/**/*.ts"]
+}
diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json
index 1ffef60..a999c8a 100644
--- a/frontend/tsconfig.json
+++ b/frontend/tsconfig.json
@@ -2,6 +2,7 @@
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
- { "path": "./tsconfig.node.json" }
+ { "path": "./tsconfig.node.json" },
+ { "path": "./tsconfig.e2e.json" }
]
}
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 65c34f3..c2a0616 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -1,9 +1,8 @@
import react, { reactCompilerPreset } from "@vitejs/plugin-react";
import babel from "@rolldown/plugin-babel";
-import { defineConfig } from "vite";
+import { defineConfig } from "vitest/config";
import tailwindcss from "@tailwindcss/vite";
-// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
@@ -26,4 +25,36 @@ export default defineConfig({
apply: "serve",
embeddedVisibility: "passive",
},
+ test: {
+ environment: "node",
+ globals: false,
+ include: ["src/**/*.{test,spec}.{ts,tsx}"],
+ setupFiles: ["./src/test/setup.ts"],
+ environmentOptions: {
+ jsdom: {
+ url: "http://pdataviewer.example.test/",
+ },
+ },
+ env: {
+ VITE_API_URL: "http://pdataviewer.example.test/api",
+ },
+ coverage: {
+ provider: "v8",
+ reportsDirectory: "./coverage",
+ include: ["src/**/*.{ts,tsx}"],
+ exclude: [
+ "src/**/*.{test,spec}.{ts,tsx}",
+ "src/**/*.d.ts",
+ "src/test/**",
+ "src/components/ui/**",
+ ],
+ reporter: ["text", "html", "lcov", "json-summary"],
+ thresholds: {
+ statements: 90,
+ branches: 80,
+ functions: 95,
+ lines: 95,
+ },
+ },
+ },
});