-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpostMessageEvent.hooks.test.ts
More file actions
418 lines (343 loc) · 15.1 KB
/
postMessageEvent.hooks.test.ts
File metadata and controls
418 lines (343 loc) · 15.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/**
* @vitest-environment jsdom
*/
import { vi } from "vitest";
import Config, { setConfigFromParams } from "../../../configManager/configManager";
import { PublicLogger } from "../../../logger/logger";
import livePreviewPostMessage from "../livePreviewEventManager";
import { LIVE_PREVIEW_POST_MESSAGE_EVENTS } from "../livePreviewEventManager.constant";
import {
OnChangeLivePreviewPostMessageEventData,
OnChangeLivePreviewPostMessageEventTypes,
HistoryLivePreviewPostMessageEventData,
} from "../types/livePreviewPostMessageEvent.type";
import {
useOnEntryUpdatePostMessageEvent,
useHistoryPostMessageEvent,
} from "../postMessageEvent.hooks";
import { isOpeningInNewTab } from "../../../common/inIframe";
// Mock dependencies
vi.mock("../../../configManager/configManager", () => ({
default: {
get: vi.fn(),
},
setConfigFromParams: vi.fn(),
}));
vi.mock("../../../logger/logger", () => ({
PublicLogger: {
error: vi.fn(),
},
}));
vi.mock("../livePreviewEventManager", () => ({
default: {
on: vi.fn(),
},
}));
vi.mock("../../../common/inIframe", () => ({
isOpeningInNewTab: vi.fn(),
}));
describe("postMessageEvent.hooks", () => {
let mockWindow: any;
let mockConfig: any;
let mockOnChange: any;
beforeEach(() => {
// Reset all mocks
vi.clearAllMocks();
// Mock window object
mockWindow = {
location: {
href: "https://example.com",
reload: vi.fn(),
},
history: {
pushState: vi.fn(),
forward: vi.fn(),
back: vi.fn(),
go: vi.fn(),
},
};
// Make location.href writable
Object.defineProperty(mockWindow.location, 'href', {
writable: true,
value: "https://example.com"
});
// Mock onChange function
mockOnChange = vi.fn();
// Setup global window mock
Object.defineProperty(global, "window", {
value: mockWindow,
writable: true,
});
// Setup default config mock
mockConfig = {
ssr: false,
onChange: mockOnChange,
};
(Config.get as unknown as { mockReturnValue: (val: any) => void }).mockReturnValue(mockConfig);
(livePreviewPostMessage?.on as unknown as { mockImplementation: (fn: any) => void })?.mockImplementation(
(event: string, callback: (...args: any[]) => void) => {
// Store the callback for manual triggering in tests
mockWindow._eventCallbacks = mockWindow._eventCallbacks || {};
mockWindow._eventCallbacks[event] = callback;
}
);
// Mock isOpeningInNewTab to return true by default
(isOpeningInNewTab as any).mockReturnValue(true);
});
afterEach(() => {
vi.resetAllMocks();
});
describe("useOnEntryUpdatePostMessageEvent", () => {
beforeEach(() => {
useOnEntryUpdatePostMessageEvent();
});
it("should register event listener for ON_CHANGE events", () => {
expect(livePreviewPostMessage?.on).toHaveBeenCalledWith(
LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE,
expect.any(Function)
);
});
describe("CSR (Client-Side Rendering) scenarios", () => {
beforeEach(() => {
mockConfig.ssr = false;
(Config.get as any).mockReturnValue(mockConfig);
});
it("should call onChange when ssr is false and no event_type", () => {
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(setConfigFromParams).toHaveBeenCalledWith({
live_preview: "test-hash",
});
expect(mockOnChange).toHaveBeenCalled();
});
it("should not call onChange when event_type is present", () => {
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
_metadata: {
event_type: OnChangeLivePreviewPostMessageEventTypes.HASH_CHANGE,
},
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(setConfigFromParams).toHaveBeenCalledWith({
live_preview: "test-hash",
});
expect(mockOnChange).not.toHaveBeenCalled();
});
});
describe("SSR (Server-Side Rendering) scenarios", () => {
beforeEach(() => {
mockConfig.ssr = true;
(Config.get as any).mockReturnValue(mockConfig);
});
it("should reload window when ssr is true and no event_type and all params present", () => {
// Set URL to include all required params so reload path is taken
mockWindow.location.href = "https://example.com?live_preview=old-hash&content_type_uid=blog&entry_uid=entry-123";
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(setConfigFromParams).toHaveBeenCalledWith({
live_preview: "test-hash",
});
expect(mockWindow.location.reload).toHaveBeenCalled();
expect(mockOnChange).not.toHaveBeenCalled();
});
it("should not reload window when event_type is present", () => {
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
_metadata: {
event_type: OnChangeLivePreviewPostMessageEventTypes.URL_CHANGE,
},
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(setConfigFromParams).toHaveBeenCalledWith({
live_preview: "test-hash",
});
expect(mockWindow.location.reload).not.toHaveBeenCalled();
expect(mockOnChange).not.toHaveBeenCalled();
});
});
describe("HASH_CHANGE event type", () => {
beforeEach(() => {
// Reset config for these tests to non-SSR
mockConfig.ssr = false;
(Config.get as any).mockReturnValue(mockConfig);
});
it("should update URL with new hash in query params", () => {
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "new-hash-value",
_metadata: {
event_type: OnChangeLivePreviewPostMessageEventTypes.HASH_CHANGE,
},
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(setConfigFromParams).toHaveBeenCalledWith({
live_preview: "new-hash-value",
});
expect(mockWindow.history.pushState).toHaveBeenCalledWith(
{},
"",
"https://example.com/?live_preview=new-hash-value"
);
});
it("should update existing live_preview param in URL", () => {
mockWindow.location.href = "https://example.com/?existing=param&live_preview=old-hash";
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "updated-hash",
_metadata: {
event_type: OnChangeLivePreviewPostMessageEventTypes.HASH_CHANGE,
},
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(setConfigFromParams).toHaveBeenCalledWith({
live_preview: "updated-hash",
});
expect(mockWindow.history.pushState).toHaveBeenCalledWith(
{},
"",
"https://example.com/?existing=param&live_preview=updated-hash"
);
});
});
describe("URL_CHANGE event type", () => {
beforeEach(() => {
// Reset config for these tests to non-SSR
mockConfig.ssr = false;
(Config.get as any).mockReturnValue(mockConfig);
});
it("should navigate to new URL when url is provided", () => {
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
url: "https://newdomain.com/new-page",
_metadata: {
event_type: OnChangeLivePreviewPostMessageEventTypes.URL_CHANGE,
},
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(setConfigFromParams).toHaveBeenCalledWith({
live_preview: "test-hash",
});
expect(mockWindow.location.href).toBe("https://newdomain.com/new-page");
});
it("should not navigate when URL_CHANGE event type is present but url is not provided", () => {
const originalHref = mockWindow.location.href;
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
_metadata: {
event_type: OnChangeLivePreviewPostMessageEventTypes.URL_CHANGE,
},
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(setConfigFromParams).toHaveBeenCalledWith({
live_preview: "test-hash",
});
expect(mockWindow.location.href).toBe(originalHref);
});
});
describe("Error handling", () => {
it("should log error and return when window is not defined", () => {
// Mock isOpeningInNewTab to return true so we enter the if block
(isOpeningInNewTab as any).mockReturnValue(true);
// Mock window as undefined
Object.defineProperty(global, "window", {
value: undefined,
writable: true,
});
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(PublicLogger.error).toHaveBeenCalledWith("window is not defined");
// Restore window for other tests
Object.defineProperty(global, "window", {
value: mockWindow,
writable: true,
});
});
it("should handle errors in try-catch block", () => {
// Mock Config.get to throw an error
(Config.get as any).mockImplementation(() => {
throw new Error("Config error");
});
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(PublicLogger.error).toHaveBeenCalledWith(
"Error handling live preview update:",
expect.any(Error)
);
});
it("should handle errors when setConfigFromParams throws", () => {
(setConfigFromParams as any).mockImplementation(() => {
throw new Error("setConfigFromParams error");
});
const eventData: OnChangeLivePreviewPostMessageEventData = {
hash: "test-hash",
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.ON_CHANGE];
callback({ data: eventData });
expect(PublicLogger.error).toHaveBeenCalledWith(
"Error handling live preview update:",
expect.any(Error)
);
});
});
});
describe("useHistoryPostMessageEvent", () => {
beforeEach(() => {
useHistoryPostMessageEvent();
});
it("should register event listener for HISTORY events", () => {
expect(livePreviewPostMessage?.on).toHaveBeenCalledWith(
LIVE_PREVIEW_POST_MESSAGE_EVENTS.HISTORY,
expect.any(Function)
);
});
it("should handle forward navigation", () => {
const eventData: HistoryLivePreviewPostMessageEventData = {
type: "forward",
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.HISTORY];
callback({ data: eventData });
expect(mockWindow.history.forward).toHaveBeenCalled();
});
it("should handle backward navigation", () => {
const eventData: HistoryLivePreviewPostMessageEventData = {
type: "backward",
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.HISTORY];
callback({ data: eventData });
expect(mockWindow.history.back).toHaveBeenCalled();
});
it("should handle reload navigation", () => {
const eventData: HistoryLivePreviewPostMessageEventData = {
type: "reload",
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.HISTORY];
callback({ data: eventData });
expect(mockWindow.history.go).toHaveBeenCalled();
});
it("should throw error for unknown event type", () => {
const eventData = {
type: "unknown" as any,
};
const callback = mockWindow._eventCallbacks[LIVE_PREVIEW_POST_MESSAGE_EVENTS.HISTORY];
expect(() => {
callback({ data: eventData });
}).toThrow("Unhandled event: unknown");
});
});
});