-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
client.test.js
594 lines (479 loc) · 20.1 KB
/
client.test.js
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import { expect } from '@playwright/test';
import { start_server, test } from '../../../utils.js';
/** @typedef {import('@playwright/test').Response} Response */
test.skip(({ javaScriptEnabled }) => !javaScriptEnabled);
test.describe.configure({ mode: 'parallel' });
test.describe('beforeNavigate', () => {
test('prevents navigation triggered by link click', async ({ clicknav, page, baseURL }) => {
await page.goto('/before-navigate/prevent-navigation');
try {
await clicknav('[href="/before-navigate/a"]', { timeout: 1000 });
expect(false).toBe(true);
} catch (/** @type {any} */ e) {
expect(e.message).toMatch('page.waitForNavigation: Timeout 1000ms exceeded');
}
expect(page.url()).toBe(baseURL + '/before-navigate/prevent-navigation');
expect(await page.innerHTML('pre')).toBe('true');
});
test('prevents navigation triggered by goto', async ({ page, app, baseURL }) => {
await page.goto('/before-navigate/prevent-navigation');
await app.goto('/before-navigate/a');
expect(page.url()).toBe(baseURL + '/before-navigate/prevent-navigation');
expect(await page.innerHTML('pre')).toBe('true');
});
test('prevents navigation triggered by back button', async ({ page, app, baseURL }) => {
await page.goto('/before-navigate/a');
await app.goto('/before-navigate/prevent-navigation');
await page.click('h1'); // The browsers block attempts to prevent navigation on a frame that's never had a user gesture.
await page.goBack();
expect(await page.innerHTML('pre')).toBe('true');
expect(page.url()).toBe(baseURL + '/before-navigate/prevent-navigation');
});
test('prevents unload', async ({ page }) => {
await page.goto('/before-navigate/prevent-navigation');
await page.click('h1'); // The browsers block attempts to prevent navigation on a frame that's never had a user gesture.
const type = new Promise((fulfil) => {
page.on('dialog', async (dialog) => {
fulfil(dialog.type());
await dialog.dismiss();
});
});
await page.close({ runBeforeUnload: true });
expect(await type).toBe('beforeunload');
});
});
test.describe('Scrolling', () => {
test('url-supplied anchor works on direct page load', async ({ page, in_view }) => {
await page.goto('/anchor/anchor#go-to-element');
expect(await in_view('#go-to-element')).toBe(true);
});
test('url-supplied anchor works on navigation to page', async ({ page, in_view, clicknav }) => {
await page.goto('/anchor');
await clicknav('#first-anchor');
expect(await in_view('#go-to-element')).toBe(true);
});
test('url-supplied anchor works when navigated from scrolled page', async ({
page,
clicknav,
in_view
}) => {
await page.goto('/anchor');
await clicknav('#second-anchor');
expect(await in_view('#go-to-element')).toBe(true);
});
test('no-anchor url will scroll to top when navigated from scrolled page', async ({
page,
clicknav
}) => {
await page.goto('/anchor');
await clicknav('#third-anchor');
expect(await page.evaluate(() => scrollY === 0)).toBeTruthy();
});
test('url-supplied anchor works when navigated from bottom of page', async ({
page,
clicknav,
in_view
}) => {
await page.goto('/anchor');
await clicknav('#last-anchor');
expect(await in_view('#go-to-element')).toBe(true);
});
test('no-anchor url will scroll to top when navigated from bottom of page', async ({
clicknav,
page
}) => {
await page.goto('/anchor');
await clicknav('#last-anchor-2');
expect(await page.evaluate(() => scrollY === 0)).toBeTruthy();
});
test('scroll is restored after hitting the back button', async ({ baseURL, clicknav, page }) => {
await page.goto('/anchor');
await page.click('#scroll-anchor');
const originalScrollY = /** @type {number} */ (await page.evaluate(() => scrollY));
await clicknav('#routing-page');
await page.goBack();
await page.waitForLoadState('networkidle');
expect(page.url()).toBe(baseURL + '/anchor#last-anchor-2');
expect(await page.evaluate(() => scrollY)).toEqual(originalScrollY);
await page.goBack();
await page.waitForLoadState('networkidle');
expect(page.url()).toBe(baseURL + '/anchor');
expect(await page.evaluate(() => scrollY)).toEqual(0);
});
test('scroll is restored after hitting the back button for an in-app cross-document navigation', async ({
page,
clicknav
}) => {
await page.goto('/scroll/cross-document/a');
const rect = await page.locator('[href="/scroll/cross-document/b"]').boundingBox();
const height = await page.evaluate(() => innerHeight);
if (!rect) throw new Error('Could not determine bounding box');
const target_scroll_y = rect.y + rect.height - height;
await page.evaluate((y) => scrollTo(0, y), target_scroll_y);
await page.click('[href="/scroll/cross-document/b"]');
expect(await page.textContent('h1')).toBe('b');
await page.waitForSelector('body.started');
await clicknav('[href="/scroll/cross-document/c"]');
expect(await page.textContent('h1')).toBe('c');
await page.goBack(); // client-side back
await page.goBack(); // native back
expect(await page.textContent('h1')).toBe('a');
await page.waitForSelector('body.started');
await page.waitForTimeout(250); // needed for the test to fail reliably without the fix
const scroll_y = await page.evaluate(() => scrollY);
expect(Math.abs(scroll_y - target_scroll_y)).toBeLessThan(50); // we need a few pixels wiggle room, because browsers
});
test('url-supplied anchor is ignored with onMount() scrolling on direct page load', async ({
page,
in_view
}) => {
await page.goto('/anchor-with-manual-scroll/anchor-onmount#go-to-element');
expect(await in_view('#abcde')).toBe(true);
});
test('url-supplied anchor is ignored with afterNavigate() scrolling on direct page load', async ({
page,
in_view,
clicknav
}) => {
await page.goto('/anchor-with-manual-scroll/anchor-afternavigate#go-to-element');
expect(await in_view('#abcde')).toBe(true);
await clicknav('[href="/anchor-with-manual-scroll/anchor-afternavigate?x=y#go-to-element"]');
expect(await in_view('#abcde')).toBe(true);
});
test('url-supplied anchor is ignored with onMount() scrolling on navigation to page', async ({
page,
clicknav,
javaScriptEnabled,
in_view
}) => {
await page.goto('/anchor-with-manual-scroll');
await clicknav('[href="/anchor-with-manual-scroll/anchor-onmount#go-to-element"]');
if (javaScriptEnabled) expect(await in_view('#abcde')).toBe(true);
else expect(await in_view('#go-to-element')).toBe(true);
});
test('app-supplied scroll and focus work on direct page load', async ({ page, in_view }) => {
await page.goto('/use-action/focus-and-scroll');
expect(await in_view('#input')).toBe(true);
await expect(page.locator('#input')).toBeFocused();
});
test('app-supplied scroll and focus work on navigation to page', async ({
page,
clicknav,
in_view
}) => {
await page.goto('/use-action');
await clicknav('[href="/use-action/focus-and-scroll"]');
expect(await in_view('#input')).toBe(true);
await expect(page.locator('input')).toBeFocused();
});
test('scroll positions are recovered on reloading the page', async ({ page, app }) => {
await page.goto('/anchor');
await page.evaluate(() => window.scrollTo(0, 1000));
await app.goto('/anchor/anchor');
await page.evaluate(() => window.scrollTo(0, 1000));
await page.reload();
expect(await page.evaluate(() => window.scrollY)).toBe(1000);
await page.goBack();
expect(await page.evaluate(() => window.scrollY)).toBe(1000);
});
test('scroll position is top of page on ssr:false reload', async ({ page }) => {
await page.goto('/no-ssr/margin');
expect(await page.evaluate(() => window.scrollY)).toBe(0);
await page.reload();
expect(await page.evaluate(() => window.scrollY)).toBe(0);
});
});
test.describe('afterNavigate', () => {
test('calls callback', async ({ page, clicknav }) => {
await page.goto('/after-navigate/a');
expect(await page.textContent('h1')).toBe('undefined -> /after-navigate/a');
await clicknav('[href="/after-navigate/b"]');
expect(await page.textContent('h1')).toBe('/after-navigate/a -> /after-navigate/b');
});
});
test.describe('a11y', () => {
test('keepfocus works', async ({ page }) => {
await page.goto('/keepfocus');
await Promise.all([
page.type('#input', 'bar'),
page.waitForFunction(() => window.location.search === '?foo=bar')
]);
await expect(page.locator('#input')).toBeFocused();
});
});
test.describe('CSS', () => {
test('applies generated component styles (hides announcer)', async ({ page, clicknav }) => {
await page.goto('/css');
await clicknav('[href="/css/other"]');
expect(
await page.evaluate(() => {
const el = document.querySelector('#svelte-announcer');
return el && getComputedStyle(el).position;
})
).toBe('absolute');
});
});
test.describe('Endpoints', () => {
test('calls a delete handler', async ({ page }) => {
await page.goto('/delete-route');
await page.click('.del');
expect(await page.innerHTML('h1')).toBe('deleted 42');
});
});
test.describe('Errors', () => {
test('client-side load errors', async ({ page }) => {
await page.goto('/errors/load-client');
expect(await page.textContent('footer')).toBe('Custom layout');
expect(await page.textContent('#message')).toBe(
'This is your custom error page saying: "Crashing now"'
);
});
test('client-side module context errors', async ({ page }) => {
await page.goto('/errors/module-scope-client');
expect(await page.textContent('footer')).toBe('Custom layout');
expect(await page.textContent('#message')).toBe(
'This is your custom error page saying: "Crashing now"'
);
});
test('client-side error from load()', async ({ page }) => {
await page.goto('/errors/load-error-client');
expect(await page.textContent('footer')).toBe('Custom layout');
expect(await page.textContent('#message')).toBe(
'This is your custom error page saying: "Not found"'
);
expect(await page.innerHTML('h1')).toBe('555');
});
test('client-side 4xx status without error from load()', async ({ page }) => {
await page.goto('/errors/load-status-without-error-client');
expect(await page.textContent('footer')).toBe('Custom layout');
expect(await page.textContent('#message')).toBe(
'This is your custom error page saying: "Error: 401"'
);
expect(await page.innerHTML('h1')).toBe('401');
});
});
test.describe('Load', () => {
test('load function is only called when necessary', async ({ app, page }) => {
await page.goto('/load/change-detection/one/a');
expect(await page.textContent('h1')).toBe('layout loads: 1');
expect(await page.textContent('h2')).toBe('x: a: 1');
await app.goto('/load/change-detection/one/a?unused=whatever');
expect(await page.textContent('h2')).toBe('x: a: 1');
await app.goto('/load/change-detection/two/b');
expect(await page.textContent('h2')).toBe('y: b: 1');
await app.goto('/load/change-detection/one/a');
expect(await page.textContent('h2')).toBe('x: a: 2');
await app.goto('/load/change-detection/one/b');
expect(await page.textContent('h2')).toBe('x: b: 3');
await app.invalidate('/load/change-detection/data.json');
expect(await page.textContent('h1')).toBe('layout loads: 2');
expect(await page.textContent('h2')).toBe('x: b: 3');
await app.invalidate('/load/change-detection/data.json');
expect(await page.textContent('h1')).toBe('layout loads: 3');
expect(await page.textContent('h2')).toBe('x: b: 3');
await app.invalidate('custom:change-detection-layout');
expect(await page.textContent('h1')).toBe('layout loads: 4');
expect(await page.textContent('h2')).toBe('x: b: 3');
await page.click('button:has-text("invalidate change-detection/data.json")');
await page.waitForFunction('window.invalidated');
expect(await page.textContent('h1')).toBe('layout loads: 5');
expect(await page.textContent('h2')).toBe('x: b: 3');
await page.click('button:has-text("invalidate all")');
await page.waitForFunction('window.invalidated');
expect(await page.textContent('h1')).toBe('layout loads: 6');
expect(await page.textContent('h2')).toBe('x: b: 4');
});
test('accessing url.hash from load errors and suggests using page store', async ({ page }) => {
await page.goto('/load/url-hash#please-dont-send-me-to-load');
expect(await page.textContent('#message')).toBe(
'This is your custom error page saying: "url.hash is inaccessible from load. Consider accessing hash from the page store within the script tag of your component."'
);
});
test('url instance methods work in load', async ({ page }) => {
await page.goto('/load/url-to-string');
expect(await page.textContent('h1')).toBe("I didn't break!");
});
if (process.env.DEV) {
test('using window.fetch causes a warning', async ({ page }) => {
const port = 5173;
/** @type {string[]} */
const warnings = [];
page.on('console', (msg) => {
if (msg.type() === 'warning') {
warnings.push(msg.text());
}
});
await page.goto('/load/window-fetch/incorrect');
expect(await page.textContent('h1')).toBe('42');
expect(warnings).toContain(
`Loading http://localhost:${port}/load/window-fetch/data.json using \`window.fetch\`. For best results, use the \`fetch\` that is passed to your \`load\` function: https://kit.svelte.dev/docs/load#input-fetch`
);
warnings.length = 0;
await page.goto('/load/window-fetch/correct');
expect(await page.textContent('h1')).toBe('42');
expect(warnings).not.toContain(
`Loading http://localhost:${port}/load/window-fetch/data.json using \`window.fetch\`. For best results, use the \`fetch\` that is passed to your \`load\` function: https://kit.svelte.dev/docs/load#input-fetch`
);
});
}
});
test.describe('Page options', () => {
test('disables router if router=false', async ({ page, clicknav }) => {
await page.goto('/no-router/a');
await page.click('button');
expect(await page.textContent('button')).toBe('clicks: 1');
await Promise.all([page.waitForNavigation(), page.click('[href="/no-router/b"]')]);
expect(await page.textContent('button')).toBe('clicks: 0');
// wait until hydration before interacting with button
await page.waitForSelector('body.started');
await page.click('button');
expect(await page.textContent('button')).toBe('clicks: 1');
// wait until hydration before attempting backwards client-side navigation
await page.waitForSelector('body.started');
await clicknav('[href="/no-router/a"]');
expect(await page.textContent('button')).toBe('clicks: 1');
await Promise.all([page.waitForNavigation(), page.click('[href="/no-router/b"]')]);
expect(await page.textContent('button')).toBe('clicks: 0');
});
test('applies generated component styles with ssr=false (hides announcer)', async ({
page,
clicknav
}) => {
await page.goto('/no-ssr');
await clicknav('[href="/no-ssr/other"]');
expect(
await page.evaluate(() => {
const el = document.querySelector('#svelte-announcer');
return el && getComputedStyle(el).position;
})
).toBe('absolute');
});
});
test.describe('Prefetching', () => {
test('prefetches programmatically', async ({ baseURL, page, app }) => {
await page.goto('/routing/a');
/** @type {string[]} */
let requests = [];
page.on('request', (r) => requests.push(r.url()));
// also wait for network processing to complete, see
// https://playwright.dev/docs/network#network-events
await Promise.all([
page.waitForResponse(`${baseURL}/routing/prefetched.json`),
app.prefetch('/routing/prefetched')
]);
// svelte request made is environment dependent
if (process.env.DEV) {
expect(requests.filter((req) => req.endsWith('+page.svelte')).length).toBe(1);
} else {
// the preload helper causes an additional request to be made in Firefox,
// so we use toBeGreaterThan rather than toBe
expect(requests.filter((req) => req.endsWith('.js')).length).toBeGreaterThan(0);
}
expect(requests.includes(`${baseURL}/routing/prefetched.json`)).toBe(true);
requests = [];
await app.goto('/routing/prefetched');
expect(requests).toEqual([]);
try {
await app.prefetch('https://example.com');
throw new Error('Error was not thrown');
} catch (/** @type {any} */ e) {
expect(e.message).toMatch('Attempted to prefetch a URL that does not belong to this app');
}
});
test('chooses correct route when hash route is prefetched but regular route is clicked', async ({
app,
page
}) => {
await page.goto('/routing/a');
await app.prefetch('/routing/prefetched/hash-route#please-dont-show-me');
await app.goto('/routing/prefetched/hash-route');
await expect(page.locator('h1')).not.toHaveText('Oopsie');
});
test('does not rerun load on calls to duplicate preload hash route', async ({ app, page }) => {
await page.goto('/routing/a');
await app.prefetch('/routing/prefetched/hash-route#please-dont-show-me');
await app.prefetch('/routing/prefetched/hash-route#please-dont-show-me');
await app.goto('/routing/prefetched/hash-route#please-dont-show-me');
await expect(page.locator('p')).toHaveText('Loaded 1 times.');
});
test('does not rerun load on calls to different preload hash route', async ({ app, page }) => {
await page.goto('/routing/a');
await app.prefetch('/routing/prefetched/hash-route#please-dont-show-me');
await app.prefetch('/routing/prefetched/hash-route#please-dont-show-me-jr');
await app.goto('/routing/prefetched/hash-route#please-dont-show-me');
await expect(page.locator('p')).toHaveText('Loaded 1 times.');
});
});
test.describe('Routing', () => {
test('navigates to a new page without reloading', async ({ app, page, clicknav }) => {
await page.goto('/routing');
await app.prefetch('/routing/a').catch((e) => {
// from error handler tests; ignore
if (!e.message.includes('Crashing now')) throw e;
});
/** @type {string[]} */
const requests = [];
page.on('request', (r) => requests.push(r.url()));
await clicknav('a[href="/routing/a"]');
expect(await page.textContent('h1')).toBe('a');
expect(requests.filter((url) => !url.endsWith('/favicon.png'))).toEqual([]);
});
test('navigates programmatically', async ({ page, app }) => {
await page.goto('/routing/a');
await app.goto('/routing/b');
expect(await page.textContent('h1')).toBe('b');
});
test('$page.url.hash is correctly set on page load', async ({ page }) => {
await page.goto('/routing/hashes/pagestore#target');
expect(await page.textContent('#window-hash')).toBe('#target');
expect(await page.textContent('#page-url-hash')).toBe('#target');
});
test('$page.url.hash is correctly set on navigation', async ({ page }) => {
await page.goto('/routing/hashes/pagestore');
expect(await page.textContent('#window-hash')).toBe('');
expect(await page.textContent('#page-url-hash')).toBe('');
await page.click('[href="#target"]');
expect(await page.textContent('#window-hash')).toBe('#target');
expect(await page.textContent('#page-url-hash')).toBe('#target');
});
test('does not normalize external path', async ({ page }) => {
const urls = [];
const { port, close } = await start_server((req, res) => {
if (req.url !== '/favicon.ico') urls.push(req.url);
res.end('ok');
});
try {
await page.goto(`/routing/slashes?port=${port}`);
await page.click(`a[href="http://localhost:${port}/with-slash/"]`);
expect(urls).toEqual(['/with-slash/']);
} finally {
await close();
}
});
});
test.describe('Shadow DOM', () => {
test('client router captures anchors in shadow dom', async ({ app, page, clicknav }) => {
await page.goto('/routing/shadow-dom');
await app.prefetch('/routing/a').catch((e) => {
// from error handler tests; ignore
if (!e.message.includes('Crashing now')) throw e;
});
/** @type {string[]} */
const requests = [];
page.on('request', (r) => requests.push(r.url()));
await clicknav('div[id="clickme"]');
expect(await page.textContent('h1')).toBe('a');
expect(requests).toEqual([]);
});
});
test('Can use browser-only global on client-only page', async ({ page, read_errors }) => {
await page.goto('/no-ssr/browser-only-global');
await expect(page.locator('p')).toHaveText('Works');
expect(read_errors('/no-ssr/browser-only-global')).toBe(undefined);
});
test('can use $app/stores from anywhere on client', async ({ page }) => {
await page.goto('/store/client-access');
await expect(page.locator('h1')).toHaveText('undefined');
await page.click('button');
await expect(page.locator('h1')).toHaveText('/store/client-access');
});