BlueGit

projects-timfalken-com microchess

Files

microchess / web / tests / pwa.mjs

pwa.mjs

pwa.mjs 2.5 KiB Download Raw
1// Service-worker event tests require no push subscription or external service.
2import assert from 'node:assert/strict';
3import { readFile } from 'node:fs/promises';
4import vm from 'node:vm';
5const handlers = {}, shown = [], opened = [], navigated = [];
6const scope = 'https://example.test/microchess/';
7let windows = [], focused = false;
8const self = {
9 addEventListener: (name, handler) => { handlers[name] = handler; },
10 skipWaiting: async () => {},
11 registration: { scope, showNotification: async (title, options) => { shown.push({ title, ...options }); } },
12 clients: { claim: async () => {}, matchAll: async () => windows, openWindow: async url => { opened.push(url); } }
13};
14vm.runInNewContext(await readFile(new URL('../sw.js', import.meta.url), 'utf8'), { self, URL });
15async function dispatch (type, fields = {}) {
16 let finished;
17 handlers[type]({ ...fields, waitUntil: promise => { finished = promise; } });
18 await finished;
19}
20await dispatch('push', { data: { json: () => ({ game: 42, body: 'Your turn against Tim.' }) } });
21assert.equal(shown[0].tag, 'game-42');
22assert.equal(shown[0].icon, scope + 'assets/app-icon-192.png');
23assert.equal(shown[0].data.game, 42);
24let closed = false;
25const notification = { data: { game: 42 }, close: () => { closed = true; } };
26await dispatch('notificationclick', { notification });
27assert(closed);
28assert.equal(opened[0], scope + '?game=42', 'Notification opens main screen within deployment subdirectory');
29windows = [{ url: scope + '?replay=abc', navigate: async url => { navigated.push(url); return { focus: async () => { focused = true; } }; } }];
30await dispatch('notificationclick', { notification });
31assert.equal(navigated[0], scope + '?game=42');
32assert(focused, 'Existing window is focused');
33assert.equal(opened.length, 1, 'Existing app window is reused');
34windows = [{ url: 'https://example.test/other-app/', navigate: async () => { throw Error('Wrong scope'); } }];
35await dispatch('notificationclick', { notification });
36assert.equal(opened.length, 2, 'Another application is not navigated');
37await dispatch('push', { data: { json: () => { throw Error('Malformed payload'); } } });
38assert.equal(shown[1].body, 'A game is waiting for you.');
39await dispatch('notificationclick', { notification: { data: { game: 'https://evil.test/' }, close: () => {} } });
40assert.equal(opened.at(-1), scope, 'Notification data cannot redirect outside app');
41console.log('PWA: notification display, subdirectory links, window reuse and malformed payload checks passed.');