Implementing the service worker
Service workers have an odd interface. For one thing, they need to rely on a variable named self
that is provided by the browser context. Then they need to attach listeners to certain events, and they need to use the event.waitUntil
function to ensure that the browser waits for its operations to finish before assuming the worker is ready.
It turns out that it’s quite difficult to set up a value for self
together with fake events within your Vitest tests. Not impossible, but difficult and laborious.
Given this complexity, the trick to implementing a testable service worker is to move most of the functionality into another module: each event becomes a simple function call, and we can test that function call rather than the event.
Then, we leave the service worker module untested. We still have the Playwright test giving us coverage, and this code isn’t likely to change once it’s complete, so it’s no big deal that this...