Overview
Produces tests/sw-lifecycle.spec.mjs: one Playwright test per service-worker lifecycle transition plus a v1 โ v2 upgrade test. The states are parsed, installing, installed, activating, activated, redundant, and statechange fires on the ServiceWorker object when its state changes (spec (opens in new window)). Most "stale after deploy" bugs are here: v2 stuck waiting behind v1, v2 active but tabs still on v1, or v1 caches left behind.
Registration itself is the input, not the subject: it is covered by add-to-homescreen-flow-tests (its install-flow reference). For the page-side workbox-window events, see workbox-tests.
When to use
Step 1 - Inventory the service worker
grep -nE "skipWaiting|clients\.claim|caches\.delete|waitUntil" src/sw.*Record whether install calls skipWaiting() and activate calls clients.claim(). skipWaiting() makes a waiting worker active without waiting for old tabs to close (MDN (opens in new window)); claim() makes an active worker control pages that are already open (MDN (opens in new window)). The expectations in Steps 4-5 depend on both.
Step 2 - Add the versioned fixture server
Copy the server from references/test-fixtures.md to tests/fixtures/sw-server.mjs, replacing its sw() body with the real service worker's install / activate logic and keeping the VERSION constant, the version-named cache, and the message handler. Start it from Playwright's webServer and run this spec with one worker.
Step 3 - Write the spec
Helpers and the three core tests (verified 15/15 passing serially on Chromium against the fixture server):
import { test, expect } from '@playwright/test';
const BASE = 'http://localhost:3000';
const setSwVersion = (request, v) => request.post(`${BASE}/__test/sw-version/${v}`);
const swVersion = (page) => page.evaluate(() => new Promise((resolve) => {
const ch = new MessageChannel();
ch.port1.onmessage = (e) => resolve(e.data);
navigator.serviceWorker.controller.postMessage('version', [ch.port2]);
}));
test.beforeEach(async ({ request }) => { await setSwVersion(request, 1); });
test('first install reaches activated', async ({ page }) => {
await page.goto(BASE + '/');
const observed = await page.evaluate(() => new Promise((resolve) => {
const states = [];
navigator.serviceWorker.register('/sw.js').then((reg) => {
const w = reg.installing ?? reg.waiting ?? reg.active;
states.push(w.state);
if (w.state === 'activated') return resolve(states);
w.addEventListener('statechange', () => {
states.push(w.state);
if (w.state === 'activated' || w.state === 'redundant') resolve(states);
});
});
}));
expect(observed).toContain('activated');
});
test('waitUntil holds the install phase', async ({ page }) => {
await page.goto(BASE + '/');
const ms = await page.evaluate(async () => {
const t0 = performance.now();
const reg = await navigator.serviceWorker.register('/sw-slow-install.js', { scope: '/slow/' });
const w = reg.installing;
await new Promise((r) => w.addEventListener('statechange', () => w.state !== 'installing' && r()));
return performance.now() - t0;
});
expect(ms).toBeGreaterThanOrEqual(1900);
});
test('v1 to v2: skipWaiting + claim flip the controller and clean caches', async ({ page, request }) => {
await page.goto(BASE + '/');
await page.waitForFunction(() => navigator.serviceWorker.controller !== null);
expect(await swVersion(page)).toBe(1);
await setSwVersion(request, 2);
const states = page.evaluate(() => new Promise(async (resolve) => {
const reg = await navigator.serviceWorker.getRegistration();
const old = reg.active;
old.addEventListener('statechange', () => old.state === 'redundant' && resolve(old.state));
}));
const found = page.evaluate(() => new Promise(async (resolve) => {
const reg = await navigator.serviceWorker.getRegistration();
reg.addEventListener('updatefound', () => resolve(true));
}));
await page.evaluate(async () => (await navigator.serviceWorker.getRegistration()).update());
expect(await found).toBe(true);
expect(await states).toBe('redundant');
await expect.poll(() => swVersion(page)).toBe(2);
await expect.poll(() => page.evaluate(() => caches.keys())).toEqual(['app-v2']);
});What each test proves:
| Test | Transition | Fails when |
|---|---|---|
| first install | installing โ activated | install handler throws or a precache URL 404s |
| waitUntil | installing held ~2 s | waitUntil missing, so fetch / push can arrive before precache finishes |
| v1 โ v2 | updatefound; v1 โ redundant; controller reports 2; only app-v2 cache left | missing skipWaiting, missing claim, or no cache cleanup |
Step 4 - Variant: no skipWaiting()
If the inventory shows no skipWaiting(), v2 must stay waiting while a v1 page is open. Replace the v1 โ v2 expectations with:
await expect.poll(() => page.evaluate(async () =>
(await navigator.serviceWorker.getRegistration()).waiting?.state)).toBe('installed');
expect(await swVersion(page)).toBe(1); // still controlled by v1then close every page, open a new one, and assert swVersion is 2.
Step 5 - Variant: skipWaiting() without claim()
v2 activates but the open page keeps controller === null or the old controller until it navigates. Assert swVersion is still 1 after redundant, then page.reload() and assert 2. A reload from Playwright is a normal reload, so the service worker handles it; a user's shift-reload bypasses the worker (MDN Service Worker API (opens in new window)).
Step 6 - When a test fails
| Failing check | Look at |
|---|---|
Never reaches activated | Errors in the worker's own console (chrome://serviceworker-internals in a headed run) and precache URLs that 404 |
updatefound never fires | The server still returns identical bytes, or the script is served from HTTP cache (Cache-Control) |
| Version stays 1 | skipWaiting() / claim() missing (Steps 4-5 decide which is intended) |
| Old cache remains | activate deletes only known names; delete every name except the current one |
| Passes alone, fails in the full run | More than one worker is flipping the server version |
Fix the cause, re-run the single test with --repeat-each=5, then the whole file.
Step 7 - Coverage matrix
Write tests/sw-lifecycle-coverage.yaml mapping each test to its transition (template in references/upgrade-path.md) and fail CI when a row has no passing test.
Anti-patterns
| Anti-pattern | Why it fails | Fix |
|---|---|---|
Polling reg.installing / waiting / active | The fields change between samples | Listen for statechange |
| Versioning via a page query parameter | update() re-fetches the same script bytes | Flip the version on the server (Step 2) |
Asserting scriptURL to tell v1 from v2 | Same URL for both versions | Ask the worker its version (swVersion) |
Fixed sleeps (setTimeout(โฆ, 500)) | Passes or fails by machine speed | Wait on events and expect.poll |
| Parallel workers sharing the version server | Tests flip each other's version | One worker for this spec |
| Exact state-array equality | Intermediate states may not be observed | toContain / final state only |
Limitations
References
Deep reference for service-worker-lifecycle-tests. Consult for the deeper recipes past the persistent-context setup and offline worked example in playwright-sw-harness.md (opens in new window): version-bump cache invalidation, service-worker-mock unit tests, and push-notification subscription tests.
Version bump + cache invalidation
Assert a v2 worker deletes the v1 caches when it activates:
test('SW v2 deletes v1 caches on activate', async ({ context, page }) => {
await page.goto('https://localhost:3000');
let sw = context.serviceWorkers()[0]
?? await context.waitForEvent('serviceworker');
const v1Caches = await sw.evaluate(() => caches.keys());
expect(v1Caches).toContain('app-v1');
// Trigger SW update (deploy v2 to test server)
await page.evaluate(() => navigator.serviceWorker.getRegistration().then(r => r?.update()));
// Wait for activation
await page.waitForFunction(() =>
navigator.serviceWorker.controller?.scriptURL.includes('v2')
);
const v2Caches = await sw.evaluate(() => caches.keys());
expect(v2Caches).toContain('app-v2');
expect(v2Caches).not.toContain('app-v1');
});Unit test the SW with service-worker-mock
For Jest/Vitest unit tests that don't need a browser:
npm install --save-dev service-worker-mockimport makeServiceWorkerEnv from 'service-worker-mock';
beforeEach(() => {
Object.assign(global, makeServiceWorkerEnv());
jest.resetModules();
});
test('install event opens cache and pre-caches assets', async () => {
await import('../src/sw.js');
await self.trigger('install');
expect(self.snapshot().caches['app-v1']).toBeDefined();
expect(self.snapshot().caches['app-v1']['/index.html']).toBeDefined();
});Push notification subscription test
test('push subscription created on registration', async ({ page, context }) => {
await context.grantPermissions(['notifications']);
await page.goto('https://localhost:3000');
const subscription = await page.evaluate(async () => {
const reg = await navigator.serviceWorker.ready;
return reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: '<base64-vapid-key>',
});
});
expect(subscription).toBeDefined();
});Pair with web-push-tests for downstream send/receive assertions.
References
General Playwright service-worker harness
View source (opens in a new tab) (opens in new window)Reference for service-worker-lifecycle-tests: the general Playwright SW test harness (context.serviceWorkers() + waitForEvent('serviceworker')), service-worker-mock unit tests, and per-cache-strategy assertions (cache-first, network-first). Per the Playwright Chrome extensions docs (opens in new window), Playwright accesses service workers via context.serviceWorkers() and persists Worker objects across MV3's ~30s auto-suspend.
When to use
How to use
Setup - Playwright persistent context
import { test, expect, chromium } from '@playwright/test';
test('service worker registers on first load', async () => {
const userDataDir = '/tmp/test-user-data';
const context = await chromium.launchPersistentContext(userDataDir, {
headless: false, // needed for SW registration in some Chromium versions
});
const page = await context.newPage();
await page.goto('https://localhost:3000');
// Wait for the SW to register
let [serviceWorker] = context.serviceWorkers();
if (!serviceWorker) {
serviceWorker = await context.waitForEvent('serviceworker');
}
expect(serviceWorker.url()).toContain('/sw.js');
await context.close();
});Per Playwright Chrome extensions docs (opens in new window), the same context.serviceWorkers() pattern applies to PWA service workers (not just extensions).
Worked example - offline fallback end to end
One test that registers the worker, drops the network, and asserts the network-first fallback renders - the smallest complete offline check:
test('registered SW serves the offline page when network drops', async () => {
const context = await chromium.launchPersistentContext('/tmp/sw-offline', {
headless: false,
});
const page = await context.newPage();
// 1. Load online so the SW installs and pre-caches
await page.goto('https://localhost:3000');
let [sw] = context.serviceWorkers();
sw ??= await context.waitForEvent('serviceworker');
expect(sw.url()).toContain('/sw.js');
await page.waitForLoadState('networkidle');
// 2. Drop the network and reload
await context.setOffline(true);
await page.reload();
// 3. The SW's offline fallback answers instead of a network error
await expect(page.locator('text=You are offline')).toBeVisible();
await context.close();
});Evaluate in the worker context
const swVersion = await serviceWorker.evaluate(() => {
return self.SW_VERSION;
});
expect(swVersion).toBe('1.4.2');
// Inspect cache contents
const cachedUrls = await serviceWorker.evaluate(async () => {
const cache = await caches.open('app-v1');
const reqs = await cache.keys();
return reqs.map(r => r.url);
});
expect(cachedUrls).toContain('https://localhost:3000/manifest.json');evaluate() proxies through the worker's JS context. Per Playwright Chrome extensions docs (opens in new window), Playwright keeps the same Worker object alive across MV3 auto-suspend (~30s) - evaluate() calls continue transparently after restart.
Cache strategies
Cache-first:
test('cache-first returns from cache, no network', async ({ page }) => {
await page.goto('https://localhost:3000');
await page.waitForLoadState('networkidle');
// Block network to force cache hits
await page.route('**/static/**', route => route.abort('failed'));
await page.reload();
// Page still renders from SW cache
await expect(page.locator('h1')).toBeVisible();
});Network-first with offline fallback:
test('network-first falls back to offline page', async ({ page, context }) => {
await page.goto('https://localhost:3000');
await page.waitForLoadState('networkidle');
await context.setOffline(true);
await page.reload();
await expect(page.locator('text=You are offline')).toBeVisible();
});Anti-patterns
| Anti-pattern | Why it fails | Fix |
|---|---|---|
Test SW with chromium.launch() (incognito) | SWs don't register in incognito-by-default contexts | Use launchPersistentContext (Setup) |
Skip waitForEvent('serviceworker') | Race condition - serviceWorkers() returns empty before registration | Always await the event (Setup) |
| Reuse user-data-dir across test runs | Stale SW from prior run answers requests | Fresh userDataDir per test (Setup) |
| Test offline by killing dev server | SW caches still serve from network until setOffline(true) | Use context.setOffline(true) (Worked example) |
| Forget to grant notifications permission | pushManager.subscribe rejects silently | context.grantPermissions(['notifications']) (see references) |
Limitations
References
Companion to service-worker-lifecycle-tests. Lifecycle tests need a server whose /sw.js changes between v1 and v2 while the page stays open, and a slow-install worker. A query parameter on the page does not do this: registration.update() re-fetches the registered script URL, so the script bytes must change on the server.
Server
The test flips the version with POST /__test/sw-version/<n>; the SW reports its version over postMessage, and its cache is named after it. Cache-Control: no-store keeps the update check from reading a cached script. Serving from http://localhost is enough: browsers treat localhost as a secure context, which service workers require (MDN secure contexts (opens in new window)).
// tests/fixtures/sw-server.mjs - serves the page and a versioned SW
import http from 'node:http';
let version = 1; // flipped by the test, never by the page
const page = `<!doctype html><title>sw</title>
<script>navigator.serviceWorker.register('/sw.js')</script>`;
const sw = (v) => `
const VERSION = ${v};
const CACHE = 'app-v' + VERSION;
self.addEventListener('install', (e) => {
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(['/'])));
self.skipWaiting(); // remove to test the waiting path
});
self.addEventListener('activate', (e) => {
e.waitUntil((async () => {
for (const k of await caches.keys()) if (k !== CACHE) await caches.delete(k);
await self.clients.claim();
})());
});
self.addEventListener('message', (e) => {
if (e.data === 'version') e.ports[0].postMessage(VERSION);
});
`;
const slowSw = `
self.addEventListener('install', (e) => {
e.waitUntil(new Promise((r) => setTimeout(r, 2000))); // slow precache
});
`;
http.createServer((req, res) => {
if (req.method === 'POST' && req.url.startsWith('/__test/sw-version/')) {
version = Number(req.url.split('/').pop());
return res.end(String(version));
}
if (req.url === '/sw.js' || req.url === '/sw-slow-install.js') {
res.setHeader('Content-Type', 'text/javascript');
res.setHeader('Cache-Control', 'no-store');
return res.end(req.url === '/sw.js' ? sw(version) : slowSw);
}
res.setHeader('Content-Type', 'text/html');
res.end(page);
}).listen(3000);The server holds one version for everyone, so run lifecycle specs with one worker (--workers=1, or a Playwright project with workers: 1). With parallel workers, one test's flip to v2 lands in another test's v1 assertions.
Playwright config
// playwright.config.mjs (lifecycle project)
export default {
testMatch: /sw-lifecycle\.spec\.mjs/,
workers: 1,
use: { browserName: 'chromium' },
webServer: { command: 'node tests/fixtures/sw-server.mjs', port: 3000 },
};webServer starts the server before the tests and stops it after (Playwright web server (opens in new window)).
Lifecycle coverage matrix and v1 -> v2 upgrade-path spec
View source (opens in a new tab) (opens in new window)Companion detail for service-worker-lifecycle-tests: the coverage matrix, and where the upgrade-path test lives.
Coverage matrix
tests/sw-lifecycle-coverage.yaml maps each spec to its state-machine cell. CI gates on every matrix row having at least one passing test.
# tests/sw-lifecycle-coverage.yaml
matrix:
fresh_install:
test: "first install reaches activated"
states: [installing, installed, activating, activated]
ref: sw-spec ServiceWorkerState enum
waituntil:
test: "waitUntil holds the install phase"
states: [installing]
ref: mdn-sw waitUntil
upgrade:
test: "v1 to v2: skipWaiting + claim flip the controller and clean caches"
states: [installed, activating, activated, redundant]
events: [updatefound, statechange]
ref: mdn-skipwaiting, mdn-claim
# add when the worker omits a call (SKILL.md Steps 4-5):
# waiting_without_skipwaiting, uncontrolled_without_claimWorked example: the v1 -> v2 upgrade-path test
The upgrade test is the third test in SKILL.md Step 3, run against the fixture server in test-fixtures.md (opens in new window). It covers updatefound, v1 activated โ redundant, the controller switching to v2 (skipWaiting + clients.claim), and v2's activate handler deleting every cache except app-v2. Steps 4-5 give the expectations for workers that skip one of the two calls.
Source references:
Get new posts by email.
Occasional email with new Testland posts and plugin releases.
Unsubscribe any time. Privacy policy