Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

service-worker-lifecycle-tests

БесплатноБез исполняемых скриптовНе проверен

Use when a service worker needs lifecycle tests, users are stuck on an old version after deploy, or caching and offline behavior is untested. Tests each state…

testlandот testland★ 18 звёзд на GitHub

Об этом скилле

service-worker-lifecycle-tests

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][sw-spec]). 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

  • A new PWA needs a baseline lifecycle spec.
  • A deploy left users on the old service worker.
  • Stale-UI reports need narrowing to skipWaiting, clients.claim, or cache cleanup.

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][mdn-skipwaiting]); claim() makes an active worker control pages that are already open ([MDN][mdn-claim]). 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 `cl
Полный SKILL.md на GitHub

Установить service-worker-lifecycle-tests в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.tessl-plugin/plugin.jsonreferences/advanced-service-worker-tests.mdreferences/playwright-sw-harness.mdreferences/test-fixtures.mdreferences/upgrade-path.md

FAQ

Что делает скилл service-worker-lifecycle-tests?

Use when a service worker needs lifecycle tests, users are stuck on an old version after deploy, or caching and offline behavior is untested. Tests each state change from installing to activated, waitUntil, skipWaiting and clients.claim, update() and a clean v1 to v2 upgrade with Playwright.

Как установить скилл service-worker-lifecycle-tests?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл service-worker-lifecycle-tests запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить service-worker-lifecycle-tests с