Skip to the code

Precache and clean up

MediumCaching

Each release of the tea shop's service worker ships with the files the shop needs offline, in a cache named for the release: this one is "tea-shop-v2". Write the two lifecycle steps that keep Cache Storage in line with the release. The starter has the release's two lists: PRECACHE_FILES, the files to store (/, /menu, /assets/app.4f1c9e.js, /assets/styles.9b2e07.css, and /offline.html), and CURRENT_CACHES, every cache this release uses ("tea-shop-v2" and its runtime cache, "tea-shop-pages-v1").

precache() returns a promise that opens "tea-shop-v2" and stores every file in PRECACHE_FILES, all or nothing: if any file fails to download, or comes back with a status that isn't ok, the promise rejects and none of the files is stored. cache.addAll() does exactly that, as the Service Workers spec defines it. onInstall(event) hands that promise to event.waitUntil(): an install whose promise rejects fails, and the browser keeps the old worker, which is what you want when the new one couldn't get its files.

cleanUp() returns a promise that deletes every cache whose name starts with "tea-shop-" and isn't in CURRENT_CACHES, and resolves, once they're all gone, with the deleted names in the order caches.keys() lists them. Leave every other cache alone: Cache Storage belongs to the whole origin, and other scripts on it may keep caches of their own. onActivate(event) hands that promise to event.waitUntil(), so the new worker doesn't handle fetches until the old caches are gone.

The tests call onInstall and onActivate with a stand-in event whose waitUntil records the promise it's given, and give you Cache Storage (useCaches()) and the network (useFetch()), which addAll() goes through.

self.addEventListener("install", onInstall);
self.addEventListener("activate", onActivate);
// Install: "tea-shop-v2" gets all five files, or the install fails and the old worker stays.
// Activate, with "tea-shop-v1", "tea-shop-v2", "tea-shop-pages-v1", and "analytics-queue" in Cache Storage:
await cleanUp(); // ["tea-shop-v1"]

What the tests check

  1. precache() stores every file in tea-shop-v2
    const cacheStorage = useCaches();
    useFetch((url) => ({ body: "contents of " + url }));
    await precache();
    expect(cacheStorage.contents()).toEqual({
      "tea-shop-v2": [
        "https://example.test/",
        "https://example.test/menu",
        "https://example.test/assets/app.4f1c9e.js",
        "https://example.test/assets/styles.9b2e07.css",
        "https://example.test/offline.html",
      ],
    });
    expect(await (await caches.match("/offline.html")).text()).toBe("contents of https://example.test/offline.html");
    
  2. one file that isn't ok fails the precache, and none is stored
    const cacheStorage = useCaches();
    useFetch((url) => (url.endsWith("/offline.html") ? { status: 404, body: "Not found" } : { body: "ok" }));
    await expect(precache()).rejects.toThrow(TypeError);
    expect(cacheStorage.contents()["tea-shop-v2"] ?? []).toEqual([]);
    
  3. a download that fails fails the precache too
    const cacheStorage = useCaches();
    useFetch((url) => {
      if (url.endsWith(".css")) throw new TypeError("Failed to fetch");
      return { body: "ok" };
    });
    await expect(precache()).rejects.toThrow("Failed to fetch");
    expect(cacheStorage.contents()["tea-shop-v2"] ?? []).toEqual([]);
    
  4. onInstall hands the precache promise to waitUntil
    useCaches();
    useFetch(() => ({ body: "ok" }));
    const event = { waitUntil: spy() };
    onInstall(event);
    expect(event.waitUntil.callCount).toBe(1);
    await event.waitUntil.calls[0].args[0];
    expect(await (await caches.open("tea-shop-v2")).keys()).toHaveLength(5);
    
  5. a failed precache fails the install
    useCaches();
    useFetch((url) => (url.endsWith("/menu") ? { status: 503, body: "Back soon" } : { body: "ok" }));
    const event = { waitUntil: spy() };
    onInstall(event);
    expect(event.waitUntil.callCount).toBe(1);
    await expect(event.waitUntil.calls[0].args[0]).rejects.toThrow(TypeError);
    
  6. cleanUp() deletes the shop's old caches, keeps the current ones, and says which it deleted
    useCaches();
    for (const name of ["tea-shop-v1", "tea-shop-v2", "tea-shop-pages-v0", "tea-shop-pages-v1"]) await caches.open(name);
    expect(await cleanUp()).toEqual(["tea-shop-v1", "tea-shop-pages-v0"]);
    expect(await caches.keys()).toEqual(["tea-shop-v2", "tea-shop-pages-v1"]);
    
  7. cleanUp() leaves the caches that aren't the shop's alone
    useCaches();
    for (const name of ["analytics-queue", "tea-shop-v1", "workbox-precache-v2"]) await caches.open(name);
    expect(await cleanUp()).toEqual(["tea-shop-v1"]);
    expect(await caches.keys()).toEqual(["analytics-queue", "workbox-precache-v2"]);
    
  8. with nothing old, cleanUp() deletes nothing
    useCaches();
    await caches.open("tea-shop-v2");
    expect(await cleanUp()).toEqual([]);
    expect(await caches.keys()).toEqual(["tea-shop-v2"]);
    
  9. onActivate hands waitUntil a promise that settles once every old cache is gone
    useCaches();
    await caches.open("tea-shop-v1");
    await caches.open("tea-shop-pages-v0");
    const event = { waitUntil: spy() };
    onActivate(event);
    expect(event.waitUntil.callCount).toBe(1);
    await event.waitUntil.calls[0].args[0];
    expect(await caches.keys()).toEqual([]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).