F2: one shared cache version renamed every cache, so the v2 bump that drops the v1 API cache (dinner responses with the pasted recipe_url) also deleted saved photos, fonts and the precache. Each cache now carries its own version in cacheVersions; only api is v2, so activate deletes mealquest-api-v1 and keeps mealquest-precache-v1, -media-v1 and -fonts-v1. F3: replace the source-text activation test with src/sw.test.ts, which loads the worker with the Workbox precache and router stubbed, dispatches activate against mocked Cache Storage, and asserts caches.delete is called for mealquest-api-v1 only. tsconfig.sw.json type-checks the test with the worker's types. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
48 lines
1.6 KiB
TypeScript
48 lines
1.6 KiB
TypeScript
// Runs the service worker's activate handler against mocked Cache Storage,
|
|
// with the Workbox precache and router stubbed out. tsconfig.sw.json checks
|
|
// this file with the worker's types, like src/sw.ts itself.
|
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
vi.mock('workbox-precaching', () => ({
|
|
PrecacheFallbackPlugin: class {},
|
|
matchPrecache: vi.fn(),
|
|
precacheAndRoute: vi.fn(),
|
|
}))
|
|
vi.mock('workbox-routing', () => ({ registerRoute: vi.fn() }))
|
|
|
|
describe('service worker activation', () => {
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals()
|
|
})
|
|
|
|
it('deletes the v1 API cache and keeps the precache, photo and font caches', async () => {
|
|
// A household on the v1 worker: its API cache held dinners with the
|
|
// pasted recipe_url; its photos and fonts are not in the precache.
|
|
const names = [
|
|
'mealquest-precache-v1',
|
|
'mealquest-api-v1',
|
|
'mealquest-media-v1',
|
|
'mealquest-fonts-v1',
|
|
'other-app-cache',
|
|
]
|
|
const cacheStorage = {
|
|
keys: vi.fn(async () => names),
|
|
delete: vi.fn(async () => true),
|
|
}
|
|
vi.stubGlobal('caches', cacheStorage)
|
|
vi.stubGlobal('__WB_MANIFEST', [])
|
|
await import('./sw')
|
|
|
|
const pending: Promise<unknown>[] = []
|
|
const activate = Object.assign(new Event('activate'), {
|
|
waitUntil: (promise: Promise<unknown>) => pending.push(promise),
|
|
})
|
|
self.dispatchEvent(activate)
|
|
await Promise.all(pending)
|
|
|
|
expect(pending).toHaveLength(1)
|
|
expect(cacheStorage.delete).toHaveBeenCalledWith('mealquest-api-v1')
|
|
expect(cacheStorage.delete).toHaveBeenCalledTimes(1)
|
|
})
|
|
})
|