forked from ReforgeHQ/sdk-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprefetch.test.ts
More file actions
76 lines (60 loc) · 2.1 KB
/
prefetch.test.ts
File metadata and controls
76 lines (60 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* @jest-environment jsdom
*/
import { prefetchReforgeConfig, Reforge } from "./reforge";
import Context from "./context";
describe("prefetchReforgeConfig", () => {
const sdkKey = "test-sdk-key";
const context = new Context({ user: { id: "123" } });
beforeEach(() => {
// Reset window object
(window as any).REFORGE_SDK_PREFETCH_PROMISE = undefined;
jest.clearAllMocks();
});
it("should set REFORGE_SDK_PREFETCH_PROMISE on window", () => {
// Mock fetch to return a promise
global.fetch = jest.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve({ evaluations: {} }),
} as Response)
);
prefetchReforgeConfig({ sdkKey, context });
expect((window as any).REFORGE_SDK_PREFETCH_PROMISE).toBeDefined();
expect((window as any).REFORGE_SDK_PREFETCH_PROMISE).toBeInstanceOf(Promise);
});
it("should pass correct parameters to loader", async () => {
global.fetch = jest.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve({ evaluations: {} }),
} as Response)
);
prefetchReforgeConfig({ sdkKey, context });
await (window as any).REFORGE_SDK_PREFETCH_PROMISE;
expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining(context.encode()),
expect.anything()
);
});
it("should not make a second API call when initializing Reforge with prefetch", async () => {
// 1. Mock fetch
global.fetch = jest.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve({ evaluations: {} }),
} as Response)
);
// 2. Start prefetch
prefetchReforgeConfig({ sdkKey, context });
// Verify prefetch started
expect(global.fetch).toHaveBeenCalledTimes(1);
// 3. Initialize Reforge
const reforgeInstance = new Reforge();
await reforgeInstance.init({ sdkKey, context });
// 4. Verify fetch was NOT called again
expect(global.fetch).toHaveBeenCalledTimes(1);
// Verify window global was cleared (as per loader logic)
expect((window as any).REFORGE_SDK_PREFETCH_PROMISE).toBeUndefined();
});
});