Debian Codegraph @

tests/unit/hooks.test.ts

raw
1 import { describe, expect, it, vi } from 'vitest';
2 import Swup from '../../src/Swup.js';
3 import { Hooks, type HookHandler, type HookDefaultHandler } from '../../src/modules/Hooks.js';
4 import { type Visit, createVisit } from '../../src/modules/Visit.js';
5
6 class SwupWithPublicVisitMethods extends Swup {
7 public createVisit = createVisit;
8 }
9
10 const swup = new SwupWithPublicVisitMethods();
11
12 describe('Hook registry', () => {
13 it('should add handlers', () => {
14 const swup = new Swup();
15 const handler = vi.fn();
16
17 // Make private fields public for this test
18 const HooksWithAccess = class extends Hooks {
19 getRegistry() {
20 return this.registry;
21 }
22 };
23 const hooks = new HooksWithAccess(swup);
24
25 hooks.on('enable', handler);
26 const ledger = hooks.getRegistry().get('enable');
27
28 expect(ledger).toBeDefined();
29 expect(ledger).toBeInstanceOf(Map);
30 expect(ledger!.size).toBe(1);
31
32 const registrations = Array.from(ledger!.values());
33 const registration = registrations.find((reg) => reg.handler === handler);
34
35 expect(registration?.handler).toEqual(handler);
36 });
37
38 it('should remove handlers', async () => {
39 const swup = new Swup();
40 const handler1 = vi.fn();
41 const handler2 = vi.fn();
42
43 swup.hooks.on('enable', handler1);
44 swup.hooks.on('enable', handler2);
45
46 await swup.hooks.call('enable', undefined, undefined);
47
48 expect(handler1).toBeCalledTimes(1);
49 expect(handler2).toBeCalledTimes(1);
50
51 swup.hooks.off('enable', handler2);
52
53 await swup.hooks.call('enable', undefined, undefined);
54
55 expect(handler1).toBeCalledTimes(2);
56 expect(handler2).toBeCalledTimes(1);
57 });
58
59 it('should return a function to unregister the handler', async () => {
60 const swup = new Swup();
61 const handler1 = vi.fn();
62 const handler2 = vi.fn();
63
64 const unregister1 = swup.hooks.on('enable', handler1);
65 const unregister2 = swup.hooks.on('enable', handler2);
66
67 expect(unregister1).toBeTypeOf('function');
68
69 await swup.hooks.call('enable', undefined, undefined);
70
71 expect(handler1).toBeCalledTimes(1);
72 expect(handler2).toBeCalledTimes(1);
73
74 unregister2();
75
76 await swup.hooks.call('enable', undefined, undefined);
77
78 expect(handler1).toBeCalledTimes(2);
79 expect(handler2).toBeCalledTimes(1);
80 });
81
82 it('should trigger custom handlers', async () => {
83 const swup = new Swup();
84 const handler = vi.fn();
85
86 swup.hooks.on('enable', handler);
87
88 await swup.hooks.call('enable', undefined, undefined);
89
90 expect(handler).toBeCalledTimes(1);
91 });
92
93 it('should only trigger custom handlers once if requested', async () => {
94 const swup = new Swup();
95 const handler = vi.fn();
96
97 swup.hooks.on('enable', handler, { once: true });
98
99 await swup.hooks.call('enable', undefined, undefined, () => {});
100 await swup.hooks.call('enable', undefined, undefined, () => {});
101
102 expect(handler).toBeCalledTimes(1);
103 });
104
105 it('should only trigger custom handlers once if using alias', async () => {
106 const swup = new Swup();
107 const handler = vi.fn();
108
109 swup.hooks.once('enable', handler);
110
111 await swup.hooks.call('enable', undefined, undefined, () => {});
112 await swup.hooks.call('enable', undefined, undefined, () => {});
113
114 expect(handler).toBeCalledTimes(1);
115 });
116
117 it('should trigger original handlers', async () => {
118 const swup = new Swup();
119 const handler = vi.fn();
120
121 await swup.hooks.call('enable', undefined, undefined, handler);
122
123 expect(handler).toBeCalledTimes(1);
124 });
125
126 it('should allow triggering custom handlers before original handler', async () => {
127 const swup = new Swup();
128
129 let called: Array<string> = [];
130 const handlers = {
131 before: () => {
132 called.push('before');
133 },
134 original: () => {
135 called.push('original');
136 },
137 normal: () => {
138 called.push('normal');
139 },
140 after: () => {
141 called.push('after');
142 }
143 };
144
145 swup.hooks.on('disable', handlers.before, { before: true });
146 swup.hooks.on('disable', handlers.normal, {});
147 swup.hooks.on('disable', handlers.after, {});
148
149 await swup.hooks.call('disable', undefined, undefined, handlers.original);
150
151 expect(called).toEqual(['before', 'original', 'normal', 'after']);
152 });
153
154 it('should sort custom handlers by priority', async () => {
155 const swup = new Swup();
156
157 let called: Array<number> = [];
158 const handlers = {
159 1: () => {
160 called.push(1);
161 },
162 2: () => {
163 called.push(2);
164 },
165 3: () => {
166 called.push(3);
167 },
168 4: () => {
169 called.push(4);
170 },
171 5: () => {
172 called.push(5);
173 },
174 6: () => {
175 called.push(6);
176 },
177 7: () => {
178 called.push(7);
179 },
180 8: () => {
181 called.push(8);
182 },
183 9: () => {
184 called.push(9);
185 }
186 };
187
188 swup.hooks.on('disable', handlers['1'], { priority: 2, before: true });
189 swup.hooks.on('disable', handlers['2'], { priority: -1, before: true });
190 swup.hooks.on('disable', handlers['3'], { priority: 1 });
191 swup.hooks.on('disable', handlers['9']);
192 swup.hooks.on('disable', handlers['4']);
193 swup.hooks.on('disable', handlers['8'], { priority: 4 });
194 swup.hooks.on('disable', handlers['7'], { priority: 4 });
195
196 await swup.hooks.call('disable', undefined, undefined, handlers['5']);
197
198 expect(called).toEqual([2, 1, 5, 9, 4, 3, 8, 7]);
199 });
200
201 it('should allow replacing original handlers', async () => {
202 const swup = new Swup();
203 const customHandler = vi.fn();
204 const defaultHandler = vi.fn();
205
206 swup.hooks.on('enable', customHandler, { replace: true });
207
208 await swup.hooks.call('enable', undefined, undefined, defaultHandler);
209
210 expect(defaultHandler).toBeCalledTimes(0);
211 expect(customHandler).toBeCalledTimes(1);
212 });
213
214 it('should only execute the last replacing handler', async () => {
215 const swup = new Swup();
216 const firstHandler = vi.fn();
217 const secondHandler = vi.fn();
218 const defaultHandler = vi.fn();
219
220 swup.hooks.on('enable', firstHandler, { replace: true });
221 swup.hooks.on('enable', secondHandler, { replace: true });
222
223 await swup.hooks.call('enable', undefined, undefined, defaultHandler);
224
225 expect(defaultHandler).toBeCalledTimes(0);
226 expect(firstHandler).toBeCalledTimes(0);
227 expect(secondHandler).toBeCalledTimes(1);
228 });
229
230 it('should pass original handler into replacing handlers', async () => {
231 const swup = new Swup();
232 const args = { foo: 'bar' };
233 const customHandler = vi.fn((c, a, handler) => handler(c, args));
234 const defaultHandler = vi.fn();
235 const visit = swup.visit;
236
237 swup.hooks.on('enable', customHandler, { replace: true });
238
239 await swup.hooks.call('enable', undefined, undefined, defaultHandler);
240
241 expect(customHandler).toBeCalledWith(visit, undefined, defaultHandler);
242 expect(defaultHandler).toBeCalledWith(visit, args);
243 });
244
245 it('should return result of replacing handler', async () => {
246 const swup = new Swup();
247 const customHandler = vi.fn(async () => 'foo');
248 const defaultHandler = vi.fn(async () => 'bar');
249
250 swup.hooks.on('enable', customHandler, { replace: true });
251
252 const result = await swup.hooks.call('enable', undefined, undefined, defaultHandler);
253
254 expect(result).toEqual('foo');
255 });
256
257 it('should pass previous handler into nested replacing handlers', async () => {
258 const swup = new Swup();
259 const args1 = { foo: 'bar' };
260 const args2 = { foo: 'baz' };
261 const args3 = { foo: 'bag' };
262 const defaultHandler = vi.fn();
263 const firstHandler = vi.fn((c, a, handler) => handler(c, args1));
264 const secondHandler = vi.fn((c, a, handler) => handler(c, args2));
265 const thirdHandler = vi.fn((c, a, handler) => handler(c, args3, handler));
266 const visit = swup.visit;
267
268 swup.hooks.on('enable', firstHandler, { replace: true });
269 swup.hooks.on('enable', secondHandler, { replace: true });
270 swup.hooks.on('enable', thirdHandler, { replace: true });
271
272 await swup.hooks.call('enable', undefined, undefined, defaultHandler);
273
274 expect(defaultHandler).toBeCalledWith(visit, args1);
275 expect(thirdHandler).toBeCalledWith(visit, undefined, expect.any(Function));
276 expect(secondHandler).toBeCalledWith(visit, args3, expect.any(Function));
277 expect(firstHandler).toBeCalledWith(visit, args2, expect.any(Function));
278 });
279
280 it('should not pass original handler into normal handlers', async () => {
281 const swup = new Swup();
282 const listener = vi.fn();
283 const handler = vi.fn();
284 const visit = swup.visit;
285
286 swup.hooks.on('enable', listener);
287
288 await swup.hooks.call('enable', undefined, undefined, handler);
289
290 expect(listener).toBeCalledWith(visit, undefined, undefined);
291 });
292
293 it('should allow replacing original handler only once', async () => {
294 const swup = new Swup();
295 const customHandler = vi.fn();
296 const defaultHandler = vi.fn();
297
298 swup.hooks.on('enable', customHandler, { replace: true, once: true });
299
300 await swup.hooks.call('enable', undefined, undefined, defaultHandler);
301 expect(defaultHandler).toBeCalledTimes(0);
302 expect(customHandler).toBeCalledTimes(1);
303
304 await swup.hooks.call('enable', undefined, undefined, defaultHandler);
305 expect(defaultHandler).toBeCalledTimes(1);
306 expect(customHandler).toBeCalledTimes(1);
307 });
308
309 it('should trigger hook handler with visit and args', async () => {
310 const swup = new SwupWithPublicVisitMethods();
311 const handler: HookHandler<'history:popstate'> = vi.fn();
312 const visit = swup.visit;
313 const customVisit = swup.createVisit({ to: '' });
314 const args = { event: new PopStateEvent('') };
315
316 swup.hooks.on('history:popstate', handler);
317
318 // Trigger with specific visit
319 await swup.hooks.call('history:popstate', visit, args);
320 await swup.hooks.call('history:popstate', customVisit, args);
321 // Trigger without specific visit, i.e. with fallback visit
322 await swup.hooks.call('history:popstate', undefined, args);
323
324 expect(handler).toBeCalledTimes(3);
325 expect(handler).toHaveBeenNthCalledWith(1, visit, args, undefined);
326 expect(handler).toHaveBeenNthCalledWith(2, customVisit, args, undefined);
327 expect(handler).toHaveBeenNthCalledWith(3, visit, args, undefined);
328 });
329
330 it('should accept legacy argument position', async () => {
331 const swup = new SwupWithPublicVisitMethods();
332 const handler: HookHandler<'history:popstate'> = vi.fn();
333 const enableHandler: HookHandler<'enable'> = vi.fn();
334 const defaultHandler: HookDefaultHandler<'history:popstate'> = vi.fn();
335 const visit = swup.visit;
336 const args = { event: new PopStateEvent('') };
337
338 swup.hooks.on('history:popstate', handler);
339 swup.hooks.on('enable', enableHandler);
340
341 // Trigger with legacy argument position
342 await swup.hooks.call('history:popstate', args, defaultHandler);
343 await swup.hooks.call('history:popstate', args);
344 await swup.hooks.call('enable', undefined, undefined);
345
346 expect(handler).toBeCalledTimes(2);
347 expect(handler).toHaveBeenNthCalledWith(1, visit, args, undefined);
348 expect(handler).toHaveBeenNthCalledWith(2, visit, args, undefined);
349 expect(enableHandler).toHaveBeenNthCalledWith(1, visit, undefined, undefined);
350
351 expect(defaultHandler).toBeCalledTimes(1);
352 expect(defaultHandler).toHaveBeenNthCalledWith(1, visit, args, undefined);
353 });
354
355 it('should swallow exceptions in user handlers', async () => {
356 const swup = new Swup();
357 const handlerWithError = vi.fn(() => {
358 throw new Error('UserError');
359 });
360
361 swup.hooks.on('enable', handlerWithError);
362 await expect(swup.hooks.call('enable', undefined, undefined)).resolves.toBeUndefined();
363 expect(handlerWithError).toBeCalledTimes(1);
364 });
365
366 it('should re-throw exceptions in default handlers', async () => {
367 const swup = new Swup();
368 const handlerWithError = vi.fn(() => {
369 throw new Error('UserError');
370 });
371
372 swup.hooks.before('enable', handlerWithError); // run before default handler
373 await expect(() => swup.hooks.call('enable', undefined, undefined, handlerWithError)).rejects.toThrow(/^UserError$/);
374 expect(handlerWithError).toBeCalledTimes(2);
375 });
376
377 it('should register hook handlers from options', async function () {
378 const hookSpy = vi.spyOn(Hooks.prototype, 'on');
379 const handler = vi.fn();
380 const swup = new Swup({ hooks: { 'visit:start': handler } });
381
382 await swup.hooks.call('visit:start', undefined, undefined);
383
384 expect(hookSpy).toBeCalledTimes(1);
385 expect(hookSpy).toBeCalledWith('visit:start', handler, {});
386 expect(handler).toBeCalledTimes(1);
387 });
388
389 it('should accept hook registration modifiers from options', async function () {
390 const hookSpy = vi.spyOn(Hooks.prototype, 'on');
391 const handler = vi.fn();
392 const swup = new Swup({
393 hooks: {
394 'visit:start': handler,
395 'visit:start.before': handler,
396 'visit:start.once': handler,
397 'visit:start.once.before': handler
398 }
399 });
400
401 expect(hookSpy).toBeCalledTimes(4);
402 expect(hookSpy).toBeCalledWith('visit:start', handler, {});
403 expect(hookSpy).toBeCalledWith('visit:start', handler, { before: true });
404 expect(hookSpy).toBeCalledWith('visit:start', handler, { once: true });
405 expect(hookSpy).toBeCalledWith('visit:start', handler, { once: true, before: true });
406 });
407 });
408
409 describe('Types', () => {
410 it('error when necessary', async () => {
411 const swup = new Swup();
412
413 // @ts-expect-no-error
414 swup.hooks.on(
415 'history:popstate',
416 (visit: Visit, { event }: { event: PopStateEvent }) => {}
417 );
418 // @ts-expect-no-error
419 await swup.hooks.call('history:popstate', undefined, { event: new PopStateEvent('') });
420
421 // @ts-expect-error: first arg must be Visit object
422 swup.hooks.on('history:popstate', ({ event: MouseEvent }) => {});
423 // @ts-expect-error: event arg must be PopStateEvent
424 swup.hooks.on('history:popstate', (visit: Visit, { event }: { event: MouseEvent }) => {});
425 // @ts-expect-error: event arg must be PopStateEvent
426 await swup.hooks.call('history:popstate', undefined, { event: new MouseEvent('') });
427 // @ts-expect-error: handler arg must be optional: handler?
428 swup.hooks.replace('enable', (visit: Visit, args: undefined, handler: HookDefaultHandler<'enable'>) => {});
429 });
430 });