Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { showBootError } from "./lib/bootError";
4
5class BootElement extends EventTarget {
6 children: BootElement[] = [];
7 textContent = "";
8
9 constructor(readonly tagName: string) {
10 super();
11 }
12
13 setAttribute() {}
14
15 append(child: BootElement) {
16 this.children.push(child);
17 }
18
19 replaceChildren(...children: BootElement[]) {
20 this.children = children;
21 }
22
23 get text(): string {
24 return this.textContent + this.children.map((child) => child.text).join(" ");
25 }
26}
27
28describe("app startup failures", () => {
29 let bootShell: BootElement | null;
30
31 beforeEach(() => {
32 vi.resetModules();
33 vi.doMock("./main", () => {
34 throw new Error("@vitejs/plugin-react can't detect preamble. Something is wrong.");
35 });
36 bootShell = new BootElement("div");
37 vi.stubGlobal("document", {
38 getElementById: () => bootShell,
39 createElement: (tagName: string) => new BootElement(tagName),
40 });
41 vi.spyOn(console, "error").mockImplementation(() => {});
42 });
43
44 it("shows failures from asynchronous app startup", async () => {
45 vi.doMock("./main", () => ({ startup: Promise.reject(new Error("Startup chunks failed")) }));
46
47 await import("./bootstrap");
48 await vi.dynamicImportSettled();
49
50 expect(bootShell?.text).toContain("Startup chunks failed");
51 });
52
53 afterEach(() => {
54 vi.unstubAllGlobals();
55 vi.unstubAllEnvs();
56 vi.restoreAllMocks();
57 });
58
59 it("replaces the splash when an app import throws before main can run", async () => {
60 const reload = vi.fn();
61 vi.stubGlobal("window", { location: { reload } });
62
63 await import("./bootstrap");
64 await vi.dynamicImportSettled();
65
66 expect(bootShell?.text).toContain("T3 Code could not load.");
67 const reloadButton = bootShell?.children[0]?.children.find(
68 (element) => element.tagName === "button",
69 );
70 expect(reloadButton?.text).toBe("Reload");
71 reloadButton?.dispatchEvent(new Event("click"));
72 expect(reload).toHaveBeenCalledOnce();
73 });
74
75 it.each([true, false])("shows startup error details only in dev mode, DEV=%s", (dev) => {
76 vi.stubEnv("DEV", dev);
77
78 showBootError(new Error("internal module path"));
79
80 expect(bootShell?.text).toContain("T3 Code could not load.");
81 expect(bootShell?.text.includes("internal module path")).toBe(dev);
82 });
83
84 it("does not replace the app after React removes the splash", () => {
85 bootShell = null;
86 const createElement = vi.spyOn(document, "createElement");
87
88 showBootError(new Error("late failure"));
89
90 expect(createElement).not.toHaveBeenCalled();
91 });
92});