Open History to see the last commit
1// @vitest-environment happy-dom
2import { act } from "react";
3import { createRoot } from "react-dom/client";
4import type { Root } from "react-dom/client";
5import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6
7import { setNetworkConfig } from "@/api/network-config";
8import { accountCollection, foldersCollection, notesCollection } from "@/db/collections";
9
10import { AnalyticsCharts } from "./analytics-charts";
11
12(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
13
14/** Whether loading the chart module fails, like a chunk that can't be fetched. */
15const chartsImport = vi.hoisted(() => ({ fail: true }));
16
17vi.mock("./charts", () => {
18 if (chartsImport.fail) throw new Error("Failed to fetch dynamically imported module");
19 return {
20 FolderBarChart: ({ measure }: { measure: string }) => <svg data-chart={measure} />,
21 DayBarChart: () => <svg data-chart="days" />,
22 };
23});
24
25let root: Root;
26let container: HTMLElement;
27
28beforeAll(async () => {
29 setNetworkConfig({ latencyMs: 0 });
30 await Promise.all([
31 foldersCollection.preload(),
32 notesCollection.preload(),
33 accountCollection.preload(),
34 ]);
35});
36
37beforeEach(() => {
38 container = document.createElement("div");
39 document.body.append(container);
40 // Like the app's root error screen: an error no boundary catches takes the whole tree down.
41 root = createRoot(container, { onUncaughtError: () => {} });
42 // React logs errors caught by error boundaries; they're expected here.
43 vi.spyOn(console, "error").mockImplementation(() => {});
44});
45
46afterEach(() => {
47 act(() => root.unmount());
48 container.remove();
49 vi.restoreAllMocks();
50});
51
52/**
53 * Runs `step` in act() and lets lazy imports settle. act() rethrows render
54 * errors no boundary caught; they're kept so the assertions can show what
55 * the reader is left with.
56 */
57async function run(step: () => void | Promise<void>) {
58 const errors: unknown[] = [];
59 const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
60 for (const callback of [async () => step(), ...Array.from({ length: 10 }, () => tick)]) {
61 try {
62 await act(callback);
63 } catch (error) {
64 errors.push(error);
65 }
66 }
67 return errors;
68}
69
70describe("when the chart library fails to load", () => {
71 it("keeps the page and its tables, says so in place of each chart, and retries", async () => {
72 chartsImport.fail = true;
73 const errors = await run(() =>
74 root.render(
75 <main>
76 <p>The guide</p>
77 <AnalyticsCharts variant="mac" />
78 </main>,
79 ),
80 );
81
82 // The rest of the page is still there, tables included.
83 expect(container.textContent).toContain("The guide");
84 expect(container.textContent).toContain("Notes per folder");
85 expect(container.querySelectorAll("table")).toHaveLength(3);
86 expect(container.querySelector("table")!.textContent).toContain("Work");
87 // Each chart says it couldn't load, with a way to try again.
88 expect(container.textContent).toContain("Couldn't load the chart.");
89 const retries = [...container.querySelectorAll("button")].filter(
90 (button) => button.textContent === "Try again",
91 );
92 expect(retries).toHaveLength(3);
93 expect(container.querySelectorAll("svg[data-chart]")).toHaveLength(0);
94 expect(errors).toEqual([]);
95
96 // The network is back: one retry loads the chart module again for every chart.
97 chartsImport.fail = false;
98 expect(await run(() => retries[0]!.click())).toEqual([]);
99 expect(container.textContent).not.toContain("Couldn't load the chart.");
100 expect(
101 [...container.querySelectorAll("svg[data-chart]")].map((svg) =>
102 svg.getAttribute("data-chart"),
103 ),
104 ).toEqual(["notes", "words", "days"]);
105 expect(container.querySelectorAll("table")).toHaveLength(3);
106 });
107});