Files
ytplayer/frontend/sw.test.js

153 lines
6.0 KiB
JavaScript

'use strict';
/**
* Unit tests for the service worker's activate handler (Task #55).
*
* Bug: "Update ready / Reload now" got stuck in a loop. Root cause —
* activate() unconditionally broadcast SW_UPDATE_AVAILABLE to every open
* client, even when this activation was just the first-ever install of a
* freshly (re)registered worker (e.g. right after the "Refresh UI" button's
* hardReloadUI() wipes every cache, unregisters the SW, and hard-navigates).
* That harmless re-install re-announced "update available" and immediately
* reopened the banner the user had just dismissed.
*
* sw.js runs in a ServiceWorkerGlobalScope, which Node doesn't provide, so
* these tests load the real source into a minimal vm sandbox that mocks
* `self`, `caches`, and `self.clients`, then drive the registered
* `activate` listener directly.
*/
const { test } = require('node:test');
const assert = require('node:assert');
const vm = require('node:vm');
const fs = require('node:fs');
const path = require('node:path');
const SW_SOURCE = fs.readFileSync(path.join(__dirname, 'sw.js'), 'utf8');
// Builds a fresh sandboxed SW environment with the given starting cache keys
// and returns handles to drive/inspect it.
function loadSw(initialCacheKeys, { fetchImpl } = {}) {
const cacheStore = new Set(initialCacheKeys);
const puts = [];
const deleted = [];
const clientMessages = [];
const listeners = {};
const self_ = {
addEventListener(type, fn) {
(listeners[type] = listeners[type] || []).push(fn);
},
clients: {
async claim() {},
async matchAll() {
return [{ postMessage: (msg) => clientMessages.push(msg) }];
},
},
};
const caches_ = {
async keys() { return Array.from(cacheStore); },
async delete(key) { deleted.push(key); return cacheStore.delete(key); },
async open(key) {
cacheStore.add(key);
return { addAll: async () => {}, match: async () => undefined, put: async (url) => { puts.push(url); } };
},
};
const sandbox = {
self: self_,
caches: caches_,
fetch: fetchImpl || (async () => { throw new Error('fetch not mocked'); }),
Request: class { constructor(url, init) { this.url = url; Object.assign(this, init); } },
Response: class { constructor(body, init) { this.body = body; Object.assign(this, init); } },
URL,
console,
};
vm.createContext(sandbox);
vm.runInContext(SW_SOURCE, sandbox, { filename: 'sw.js' });
async function triggerActivate() {
let waitPromise = Promise.resolve();
const event = { waitUntil: (p) => { waitPromise = p; } };
for (const fn of listeners.activate || []) fn(event);
await waitPromise;
}
async function triggerInstall() {
let waitPromise = Promise.resolve();
const event = { waitUntil: (p) => { waitPromise = p; } };
for (const fn of listeners.install || []) fn(event);
await waitPromise;
}
return { triggerActivate, triggerInstall, deleted, puts, clientMessages, cacheStoreRemaining: () => Array.from(cacheStore) };
}
test('activate does NOT broadcast on a fresh install (only the current-version cache exists)', async () => {
const sw = loadSw(['ytplayer-v1.0.4']); // default VERSION fallback in sw.js is 'v1.0.4'
await sw.triggerActivate();
assert.deepStrictEqual(sw.clientMessages, [], 'no update banner should be triggered on first-ever install');
assert.deepStrictEqual(sw.deleted, [], 'nothing stale to evict on a fresh install');
});
test('activate DOES broadcast when an older versioned shell cache is present (genuine update)', async () => {
const sw = loadSw(['ytplayer-v1.0.4', 'ytplayer-v1.0.2']);
await sw.triggerActivate();
assert.strictEqual(sw.clientMessages.length, 1, 'a genuine version bump should notify clients once');
assert.strictEqual(sw.clientMessages[0].type, 'SW_UPDATE_AVAILABLE');
assert.deepStrictEqual(sw.deleted, ['ytplayer-v1.0.2'], 'the stale shell cache should be evicted');
});
test('activate never deletes the utility caches (thumbs/fonts), broadcast or not', async () => {
const sw = loadSw(['ytplayer-v1.0.4', 'ytplayer-thumbs', 'ytplayer-fonts']);
await sw.triggerActivate();
assert.deepStrictEqual(sw.clientMessages, [], 'utility caches alone are not a version bump');
assert.deepStrictEqual(sw.deleted, [], 'utility caches must survive activate');
assert.deepStrictEqual(
sw.cacheStoreRemaining().sort(),
['ytplayer-fonts', 'ytplayer-thumbs', 'ytplayer-v1.0.4'].sort()
);
});
test('activate reports an update and still preserves utility caches together', async () => {
const sw = loadSw(['ytplayer-v1.0.4', 'ytplayer-v1.0.2', 'ytplayer-thumbs', 'ytplayer-fonts']);
await sw.triggerActivate();
assert.strictEqual(sw.clientMessages.length, 1);
assert.deepStrictEqual(sw.deleted, ['ytplayer-v1.0.2']);
assert.deepStrictEqual(
sw.cacheStoreRemaining().sort(),
['ytplayer-fonts', 'ytplayer-thumbs', 'ytplayer-v1.0.4'].sort()
);
});
test('install fetches every shell file past the HTTP cache and retries dropped requests', async () => {
const seen = {};
const sw = loadSw([], {
fetchImpl: async (req) => {
seen[req.url] = (seen[req.url] || 0) + 1;
assert.strictEqual(req.cache, 'reload', 'must bypass the browser HTTP cache');
// The homelab link drops the first request for app.js.
if (req.url === '/app.js' && seen[req.url] === 1) throw new TypeError('network error');
return { ok: true, status: 200 };
},
});
await sw.triggerInstall();
assert.strictEqual(seen['/app.js'], 2, 'a dropped request is retried');
assert.ok(sw.puts.includes('/app.js') && sw.puts.includes('/'), 'shell files cached');
assert.deepStrictEqual(sw.deleted, []);
});
test('a failed install deletes its partial cache so activate never mistakes it for an old deploy', async () => {
const sw = loadSw([], {
fetchImpl: async (req) => (req.url === '/styles.css' ? { ok: false, status: 504 } : { ok: true, status: 200 }),
});
await assert.rejects(sw.triggerInstall(), /styles\.css/);
assert.deepStrictEqual(sw.deleted, ['ytplayer-v1.0.4'], 'partial cache removed');
assert.deepStrictEqual(sw.cacheStoreRemaining(), []);
});