Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { afterEach, expect, it, vi } from "vite-plus/test";
3
4afterEach(() => {
5 vi.unstubAllGlobals();
6 vi.resetModules();
7});
8
9function stubIndexedDb(outcomes: ReadonlyArray<"success" | "error" | "blocked">) {
10 const puts: string[] = [];
11 const database = {
12 objectStoreNames: { contains: () => true, [Symbol.iterator]: [][Symbol.iterator] },
13 transaction: () => {
14 const transaction = new EventTarget();
15 return Object.assign(transaction, {
16 objectStore: () => ({
17 getAll: () => ({ result: [] }),
18 put: (_entry: unknown, key: string) => {
19 puts.push(key);
20 queueMicrotask(() => transaction.dispatchEvent(new Event("complete")));
21 },
22 }),
23 });
24 },
25 };
26 const requests: Array<EventTarget & { result: unknown; error: unknown }> = [];
27 const open = vi.fn(() => {
28 const request = Object.assign(new EventTarget(), { result: database, error: null });
29 const outcome = outcomes[requests.length];
30 requests.push(request);
31 if (outcome) queueMicrotask(() => request.dispatchEvent(new Event(outcome)));
32 return request;
33 });
34 vi.stubGlobal("indexedDB", { open });
35 vi.stubGlobal(
36 "fetch",
37 vi.fn(
38 async () =>
39 new Response(new Uint8Array([1, 2, 3]), { headers: { "content-type": "image/png" } }),
40 ),
41 );
42 return { open, requests, puts };
43}
44
45async function cacheIcon(
46 cache: typeof import("./projectFaviconCache").projectFaviconCache,
47 cwd: string,
48) {
49 const target = { environmentId: EnvironmentId.make("env"), cwd };
50 await cache.resolve(target, `http://localhost/${cwd}.png`, new AbortController().signal);
51 await cache.flush();
52}
53
54it("reopens the database after a failed open", async () => {
55 const { open, puts } = stubIndexedDb(["error", "success"]);
56 const { projectFaviconCache } = await import("./projectFaviconCache");
57
58 await projectFaviconCache.hydrate();
59 await cacheIcon(projectFaviconCache, "a");
60 expect(open).toHaveBeenCalledTimes(2);
61 expect(puts).toHaveLength(1);
62});
63
64it("uses a blocked open once it succeeds instead of opening another", async () => {
65 const { open, requests, puts } = stubIndexedDb(["blocked"]);
66 const { projectFaviconCache } = await import("./projectFaviconCache");
67
68 await projectFaviconCache.hydrate();
69 await cacheIcon(projectFaviconCache, "a");
70
71 requests[0]!.dispatchEvent(new Event("success"));
72 await cacheIcon(projectFaviconCache, "b");
73 expect(open).toHaveBeenCalledOnce();
74 expect(puts).toHaveLength(1);
75});