Files
weerscherm/tests/js/sw.test.js
T
2026-09-11 14:48:11 +02:00

99 lines
4.1 KiB
JavaScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
/** Laadt sw.js in een minimale nep-serviceworker-omgeving en geeft de geregistreerde handlers terug. */
function loadServiceWorker({ fetchImpl }) {
const listeners = {};
const store = new Map();
const cache = {
async addAll(urls) { urls.forEach((u) => store.set(new URL(u, 'http://x/').href, new Response('shell'))); },
async put(req, res) { store.set(req.url, res); },
async match(req) { return store.get(typeof req === 'string' ? req : req.url) || undefined; },
async keys() { return [...store.keys()].map((u) => new Request(u)); },
};
const sandbox = {
self: {
addEventListener: (type, fn) => { listeners[type] = fn; },
skipWaiting: async () => {},
clients: { claim: async () => {} },
location: new URL('http://x/'),
},
caches: { open: async () => cache, keys: async () => ['weerscherm-v0', 'weerscherm-v1'], delete: async () => true },
fetch: fetchImpl,
Response, Request, Headers, URL, AbortController, setTimeout, clearTimeout, console,
};
vm.createContext(sandbox);
vm.runInContext(readFileSync(new URL('../../public/sw.js', import.meta.url), 'utf8'), sandbox);
return { listeners, store };
}
function dispatchFetch(listeners, url) {
let promise = null;
listeners.fetch({
request: new Request(url),
respondWith: (p) => { promise = p; },
});
return promise;
}
test('install caches the app shell', async () => {
const { listeners, store } = loadServiceWorker({ fetchImpl: async () => new Response('x') });
let done = null;
listeners.install({ waitUntil: (p) => { done = p; } });
await done;
assert.ok(store.has('http://x/app.js'));
assert.ok(store.has('http://x/index.html'));
});
test('API request goes to the network first and is cached', async () => {
const { listeners, store } = loadServiceWorker({
fetchImpl: async () => new Response('{"station":{}}', { status: 200, headers: { 'Content-Type': 'application/json' } }),
});
const res = await dispatchFetch(listeners, 'http://x/api/data.php');
assert.equal(res.status, 200);
assert.equal(res.headers.get('X-From-Cache'), null);
assert.ok(store.has('http://x/api/data.php'));
});
test('API request falls back to the cached response with X-From-Cache when offline', async () => {
let online = true;
const { listeners } = loadServiceWorker({
fetchImpl: async () => {
if (!online) throw new TypeError('Failed to fetch');
return new Response('{"station":{"stale":false}}', { status: 200, headers: { 'Content-Type': 'application/json' } });
},
});
await dispatchFetch(listeners, 'http://x/api/data.php');
online = false;
const res = await dispatchFetch(listeners, 'http://x/api/data.php');
assert.equal(res.status, 200);
assert.equal(res.headers.get('X-From-Cache'), '1');
assert.equal(await res.text(), '{"station":{"stale":false}}');
});
test('API request without any cache gives a 503 offline JSON', async () => {
const { listeners } = loadServiceWorker({ fetchImpl: async () => { throw new TypeError('offline'); } });
const res = await dispatchFetch(listeners, 'http://x/api/data.php');
assert.equal(res.status, 503);
assert.deepEqual(await res.json(), { errors: ['offline'] });
});
test('shell request is served from cache without hitting the network', async () => {
let calls = 0;
const { listeners, store } = loadServiceWorker({ fetchImpl: async () => { calls++; return new Response('net'); } });
store.set('http://x/styles.css', new Response('cached css'));
const res = await dispatchFetch(listeners, 'http://x/styles.css');
assert.equal(await res.text(), 'cached css');
assert.equal(calls, 0);
});
test('cross-origin and non-GET requests are left alone', () => {
const { listeners } = loadServiceWorker({ fetchImpl: async () => new Response('x') });
assert.equal(dispatchFetch(listeners, 'http://elders/api/data.php'), null);
let handled = false;
listeners.fetch({ request: new Request('http://x/api/data.php', { method: 'POST' }), respondWith: () => { handled = true; } });
assert.equal(handled, false);
});