Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/pie-night

Pie night sign-ups: hosts start an event, guests add the pies they are bringing and watch the list fill in live. Installable, with optional push notifications.

FollowForkOpen app

Files

sw.test.ts

160 lines · 5.9 KB · TypeScript
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { serviceWorkerJs } from '../src/sw.ts'

const ORIGIN = 'https://pie.example.com'
const js = serviceWorkerJs({ appBase: '', assetBase: '/assets', version: '8' })

function html(status = 200, body = '<h1>live</h1>') {
	const res = new Response(body, { status, headers: { 'content-type': 'text/html; charset=utf-8' } })
	// Node's Response constructor uses type "default"; browsers mark same-origin fetch as "basic".
	Object.defineProperty(res, 'type', { value: 'basic' })
	return res
}

function mockCaches(seed: Record<string, Response> = {}) {
	const store = new Map<string, Response>(Object.entries(seed).map(([key, res]) => [key, res.clone()]))
	const cache = {
		match(req: RequestInfo) {
			const key = typeof req === 'string' ? req : req.url
			const hit = store.get(key)
			return Promise.resolve(hit ? hit.clone() : undefined)
		},
		put(req: RequestInfo, res: Response) {
			const key = typeof req === 'string' ? req : req.url
			store.set(key, res)
			return Promise.resolve()
		},
	}
	return {
		store,
		open() {
			return Promise.resolve(cache)
		},
		match(req: RequestInfo) {
			return cache.match(req)
		},
		keys() {
			return Promise.resolve([...store.keys()])
		},
		delete(key: string) {
			return Promise.resolve(store.delete(key))
		},
	}
}

function loadPolicy(fetchImpl: typeof fetch, cachesImpl: ReturnType<typeof mockCaches>) {
	const self = {
		addEventListener() {},
		location: { origin: ORIGIN },
		clients: { claim() {}, matchAll() { return Promise.resolve([]) }, openWindow() {} },
		skipWaiting() {},
		registration: {},
	}
	const fn = new Function(
		'self',
		'caches',
		'fetch',
		`${js}
		return { networkFirst, isNetworkFailure, okHtml };`,
	)
	return fn(self, cachesImpl, fetchImpl) as {
		networkFirst: (request: Request, key: string, check: (res: Response) => boolean, fallbackKey?: string) => Promise<Response>
		isNetworkFailure: (err: unknown) => boolean
		okHtml: (res: Response) => boolean
	}
}

async function flush() {
	await new Promise((resolve) => setImmediate(resolve))
	await new Promise((resolve) => setImmediate(resolve))
}

test('service worker has no navigation timeout and only falls back on network TypeError', () => {
	assert.match(js, /isNetworkFailure/)
	assert.match(js, /err\.name === 'TypeError'/)
	assert.doesNotMatch(js, /NAV_TIMEOUT_MS/)
	assert.doesNotMatch(js, /setTimeout\s*\(/)
	new Function(js)
})

test('a slow live response is used instead of the offline page', async () => {
	const cachesImpl = mockCaches({ '/offline': html(200, '<h1>offline</h1>') })
	let calls = 0
	const fetchImpl = async () => {
		calls += 1
		await new Promise((resolve) => setTimeout(resolve, 30))
		return html(200, '<h1>live</h1>')
	}
	const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl)
	const res = await networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline')
	assert.equal(await res.text(), '<h1>live</h1>')
	assert.equal(calls, 1)
	await flush()
	assert.equal(cachesImpl.store.has('/'), true)
})

test('redirects and other non-OK responses are passed through, not treated as offline', async () => {
	const cachesImpl = mockCaches({ '/offline': html(200, '<h1>offline</h1>') })
	const fetchImpl = async () =>
		new Response(null, { status: 302, headers: { location: '/e/smith-pies', 'content-type': 'text/html' } })
	const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl)
	const res = await networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline')
	assert.equal(res.status, 302)
	assert.equal(res.headers.get('location'), '/e/smith-pies')
	await flush()
	assert.equal(cachesImpl.store.has('/'), false)
})

test('a 500 HTML page is passed through and not cached as the app shell', async () => {
	const cachesImpl = mockCaches({ '/offline': html(200, '<h1>offline</h1>') })
	const fetchImpl = async () => html(500, '<h1>error</h1>')
	const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl)
	const res = await networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline')
	assert.equal(res.status, 500)
	assert.equal(await res.text(), '<h1>error</h1>')
	await flush()
	assert.equal(cachesImpl.store.has('/'), false)
})

test('a TypeError is retried once, and a later success is used', async () => {
	const cachesImpl = mockCaches({ '/offline': html(200, '<h1>offline</h1>') })
	let calls = 0
	const fetchImpl = async () => {
		calls += 1
		if (calls === 1) throw new TypeError('Failed to fetch')
		return html(200, '<h1>retried</h1>')
	}
	const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl)
	const res = await networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline')
	assert.equal(await res.text(), '<h1>retried</h1>')
	assert.equal(calls, 2)
})

test('two network failures fall back to the cached page, or /offline if none is saved', async () => {
	const withPage = mockCaches({
		'/': html(200, '<h1>cached</h1>'),
		'/offline': html(200, '<h1>offline</h1>'),
	})
	const fetchFail = async () => {
		throw new TypeError('Failed to fetch')
	}
	const policy1 = loadPolicy(fetchFail as typeof fetch, withPage)
	const cached = await policy1.networkFirst(new Request(`${ORIGIN}/`), '/', policy1.okHtml, '/offline')
	assert.equal(await cached.text(), '<h1>cached</h1>')

	const noPage = mockCaches({ '/offline': html(200, '<h1>offline</h1>') })
	const policy2 = loadPolicy(fetchFail as typeof fetch, noPage)
	const offline = await policy2.networkFirst(new Request(`${ORIGIN}/`), '/', policy2.okHtml, '/offline')
	assert.equal(await offline.text(), '<h1>offline</h1>')
})

test('a non-TypeError rejection is not treated as offline', async () => {
	const cachesImpl = mockCaches({ '/offline': html(200, '<h1>offline</h1>') })
	const err = new Error('unexpected')
	const fetchImpl = async () => {
		throw err
	}
	const { networkFirst, okHtml } = loadPolicy(fetchImpl as typeof fetch, cachesImpl)
	await assert.rejects(() => networkFirst(new Request(`${ORIGIN}/`), '/', okHtml, '/offline'), err)
})