Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2
3const mocks = vi.hoisted(() => ({ showBootError: vi.fn().mockName("showBootError") }));
4
5vi.mock("./lib/bootError", () => ({ showBootError: mocks.showBootError }));
6
7// Mirrors Vite's build preload helper when main's CSS or JS chunk fails to load.
8vi.mock("./main", () => {
9 const error = new TypeError("Failed to fetch dynamically imported module: /assets/main.js");
10 const event = Object.assign(new Event("vite:preloadError", { cancelable: true }), {
11 payload: error,
12 });
13 window.dispatchEvent(event);
14 throw error;
15});
16
17function createStorageStub(initial: Record<string, string> = {}): Storage {
18 const store = new Map(Object.entries(initial));
19 return {
20 getItem: (key) => store.get(key) ?? null,
21 setItem: (key, value) => {
22 store.set(key, value);
23 },
24 removeItem: (key) => {
25 store.delete(key);
26 },
27 clear: () => store.clear(),
28 key: (index) => [...store.keys()][index] ?? null,
29 get length() {
30 return store.size;
31 },
32 };
33}
34
35async function bootWithFailingMainChunk(storage: Storage) {
36 vi.resetModules();
37 mocks.showBootError.mockClear();
38 const reload = vi.fn().mockName("location.reload");
39 vi.stubGlobal(
40 "window",
41 Object.assign(new EventTarget(), { sessionStorage: storage, location: { reload } }),
42 );
43 try {
44 const { boot } = await import("./bootstrap");
45 await boot;
46 return { reload, showBootError: mocks.showBootError };
47 } finally {
48 vi.unstubAllGlobals();
49 }
50}
51
52describe("bootstrap", () => {
53 it("reloads once instead of showing the boot error when the main chunk fails to load", async () => {
54 const { reload, showBootError } = await bootWithFailingMainChunk(createStorageStub());
55
56 expect(reload).toHaveBeenCalledTimes(1);
57 expect(showBootError).not.toHaveBeenCalled();
58 });
59
60 it("shows the boot error when the main chunk fails again after the reload", async () => {
61 const { reload, showBootError } = await bootWithFailingMainChunk(
62 createStorageStub({ "t3code:chunk-load-reloaded": import.meta.env.APP_VERSION }),
63 );
64
65 expect(reload).not.toHaveBeenCalled();
66 expect(showBootError).toHaveBeenCalledTimes(1);
67 });
68});