Files
clean-architecture-frontend…/tests/e2e/service-worker-update.spec.ts
T
DongHyeonka aaa782bab4 test(service-worker): 옛 탭이 지워진 route를 reload 없이 여는지 본다
문제: update spec은 옛 탭 회복을 페이지의 `fetch(removedChunk)`로만
본다. 바이트가 오는지는 알지만, B가 제어하는 A 탭에서 지워진 route를
여는 실제 경로는 아무 spec도 지나지 않는다. 워커 제어 아래 preload는
11-09 허용(`preloadunverifiable:service-worker:`) 때문에 fixture가 하나도
판정하지 못한다(리뷰 06-R9: 158줄 모두 ALLOWED). 워커가 직전 캐시로
답하지 않게 바꾼 변이(06-R10)에서 화면 단언은 통과했다. chunk 복구가
페이지를 B로 reload해 같은 not-found 화면을 그렸기 때문이다.

고른 방법: 리뷰 06-03의 (a). update spec에 test 하나를 더한다. B가
제어하는 A 탭에서 client navigation(pushState + popstate)으로 일치하지
않는 경로를 연다. `CHANGED_ROUTE_SOURCE`가 not-found 페이지라 그 경로가
지워진 chunk를 import한다. 단언:
- not-found heading이 보인다.
- 같은 문서다. navigation 전에 심은 전역 표시가 남아 있고 entry script가
  그대로다(reload 없음).
- 그 문서가 chunk를 요청했다(Resource Timing 항목, 단언이 빈 경로를
  보지 않게).
- navigation 뒤 서버 요청에 그 chunk가 없다(워커가 답했다).
- strict fixture가 허용 밖 실패 줄을 보지 않는다(기존 teardown 검사).
지워진 chunk를 찾는 코드는 기존 test와 같이 쓰도록 `removedRouteChunk`로
뺐다. Firefox는 같은 파일의 기존 격리(quarantine, 2027-03-31)를 그대로
따른다. Playwright Firefox는 워커가 페이지를 제어하지 못한다(06-R11 확인).
버린 대안: fixture가 워커 쪽 응답을 추적. Playwright 워커 network 이벤트는
Chromium 전용이다.

위험·한계: 테스트만 더했다. 지금 코드는 맞으므로 RED(부모 코드)에서도
통과한다. 결함은 변이로 보인다. 엔진마다 약 7초가 늘어난다(06-R9 기준).
WebKit에서는 chunk가 modulepreload link로 요청되어 워커 경로가 Chromium과
같은지 확인하지 않았다. 허용 패턴 자체는 그대로다.

검증: desktop batch에서 확인.
- corepack pnpm exec playwright test tests/e2e/service-worker-update.spec.ts --project=chromium --project=webkit
- 변이(06-R10과 같음, `service-worker-lifecycle.ts`의
  PREVIOUS_RELEASE_FALLBACK 분기가 `return null`): 새 test가 chromium에서
  sameDocument false(또는 fixture 실패 줄)로 실패해야 한다.

Refs: 1105/06-03
2026-11-05 22:13:53 +09:00

360 lines
13 KiB
TypeScript

import { appendFile, readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
import {
prepareServiceWorkerBuilds,
removeServiceWorkerBuilds,
startBuildServer,
type ServiceWorkerBuilds,
} from "./support/service-worker-builds.ts";
/**
* R3-6. Real-browser Service Worker checks, against real production builds.
*
* How the worker is enabled: the template's default build has
* `serviceWorker: null`, and the only supported switch is the static
* capability selection in `src/features/product-capabilities.ts`
* (`{ mode: "ACTIVE", scriptPath: "service-worker.js", handlers:
* ["PWA_STATIC_ASSETS"] }`); `scripts/build-frontend.ts` then adds the worker
* build. `support/service-worker-builds.ts` applies that selection in a temp
* copy of the repo, builds it twice (`VITE_BUILD_ID` sw-e2e-a / sw-e2e-b),
* and serves either dist from its own port per test. The copy also records
* the worker host's `onUpdateWaiting` / `onReloadRequired` callbacks, which
* the app itself does not subscribe to yet.
*
* The preview server of this suite is not used; each test uses absolute URLs.
*
* Premises (0929/11-03): the helper's three, listed in
* `support/service-worker-builds.ts`, plus one here: build B changes
* `CHANGED_ROUTE_SOURCE`, so a product that deletes that page points the
* constant at another route page. Run both Service Worker specs after turning
* the worker on (Service Worker checklist in
* `docs/architecture/optional-adapter-recipes.md`).
*/
type Probe = typeof globalThis & {
__caServiceWorkerTest?: {
host: { requestActivation(): Promise<unknown> };
events: string[];
};
};
let builds: ServiceWorkerBuilds | undefined;
// 1103/11-09. Once a worker controls the page it answers the page's script
// requests, so the fixture cannot mark them and cannot tell whether a
// preload made then was run. It names those preloads instead of calling them
// unused; here they are expected. Preloads made before the worker took
// control are still checked.
test.use({
allowedBrowserFailure: /^preloadunverifiable:service-worker:\/assets\/[\w-]+\.js$/u,
});
// B changes one route chunk on purpose. Route chunks used to differ only
// because they embedded the build ID; since 09-02 they do not, so two builds
// of the same source emit the same route chunks. A dynamically imported
// module keeps all its exports, so the extra export survives the bundler.
const CHANGED_ROUTE_SOURCE =
"src/presentation/pages/not-found-page.tsx";
test.beforeAll(async () => {
test.setTimeout(180_000);
builds = await prepareServiceWorkerBuilds({
beforeBuild: async (name, root) => {
if (name !== "b") return;
await appendFile(
path.join(root, CHANGED_ROUTE_SOURCE),
'\nexport const serviceWorkerE2eBuild = "b";\n',
);
},
});
});
test.afterAll(async () => {
await removeServiceWorkerBuilds(builds);
});
function requireBuilds(): ServiceWorkerBuilds {
if (!builds) throw new Error("Service Worker builds were not prepared.");
return builds;
}
async function waitForEvent(page: Page, prefix: string): Promise<string> {
await page.waitForFunction(
(expected) =>
(globalThis as Probe).__caServiceWorkerTest?.events.some((event) =>
event.startsWith(expected),
) === true,
prefix,
{ timeout: 60_000 },
);
const events = await page.evaluate(() => [
...((globalThis as Probe).__caServiceWorkerTest?.events ?? []),
]);
return events.find((event) => event.startsWith(prefix))!;
}
async function startOutcome(page: Page): Promise<unknown> {
return JSON.parse((await waitForEvent(page, "start:")).slice("start:".length));
}
async function hashedAssets(dist: string): Promise<string[]> {
return (await readdir(path.join(dist, "assets")))
.map((file) => `/assets/${file}`)
.sort();
}
const headerCases = [
{
name: "Content-Type: application/javascript",
headers: { javascriptContentType: "application/javascript", gzip: false },
},
{
name: "Content-Encoding: gzip with the compressed Content-Length",
headers: { javascriptContentType: "text/javascript", gzip: true },
},
] as const;
for (const { name, headers } of headerCases) {
test(`installs the static asset set served with ${name}`, async ({ page }) => {
const { dist } = requireBuilds();
const server = await startBuildServer(dist, headers);
try {
await page.goto(`${server.origin}/`);
// A failed install (CONTENT_TYPE_INVALID, BYTES_MISMATCH, ...) ends as
// FAILED/INSTALL_FAILED; a first install that worked asks for a reload.
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
const cached = await page.evaluate(async () => {
const names = (await caches.keys()).filter((cacheName) =>
cacheName.startsWith("ca-static-v1-"),
);
const cache = await caches.open(names[0] ?? "missing");
const paths = (await cache.keys())
.map((request) => new URL(request.url))
.filter((url) => url.origin === location.origin)
.map((url) => url.pathname);
return { names, paths };
});
expect(cached.names).toHaveLength(1);
// 0929/11-03. The list A's build generated, not `dist/assets`: a product
// may precache more (or fewer) files than the template does.
expect(cached.paths.sort()).toEqual(requireBuilds().precached.a);
// The server really sent the headers under test.
const assets = server.served.filter((response) =>
response.path.startsWith("/assets/"),
);
expect(assets.length).toBeGreaterThan(0);
if (headers.gzip) {
expect(assets.every((response) => response.contentEncoding === "gzip"))
.toBe(true);
expect(
assets.some(
(response) => response.contentLength < response.decodedLength,
),
).toBe(true);
} else {
expect(
assets
.filter((response) => response.path.endsWith(".js"))
.every(
(response) => response.contentType === "application/javascript",
),
).toBe(true);
}
} finally {
await server.close();
}
});
}
type BuildServer = Awaited<ReturnType<typeof startBuildServer>>;
// Playwright's Firefox never lets a worker control a page: even a trivial
// classic worker leaves `navigator.serviceWorker.controller` null after a new
// navigation (checked by hand with Playwright 1.62). With no controlled
// client, B skips `waiting` and activates by itself (`requestActivation()` then
// returns NO_WAITING_WORKER), and the fetch handler is never reached. The
// update tests therefore run where a page can be controlled. Not a product
// defect.
// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31)
const NO_CONTROLLED_PAGES =
"Playwright Firefox pages are never controlled by a service worker.";
/**
* Loads build A twice (first install, then a normal navigation), switches the
* server to B, runs the update check and activates B through the app host.
* Returns whether the second load of A was controlled by the worker.
*/
async function updateFromAToB(
page: Page,
server: BuildServer,
): Promise<{ secondLoad: unknown; controlled: boolean }> {
await page.goto(`${server.origin}/`);
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
await page.evaluate(async () => {
await navigator.serviceWorker.ready;
});
// A normal navigation. (`page.reload()` would not change anything here.)
await page.goto(`${server.origin}/`);
const secondLoad = await startOutcome(page);
const controlled = await page.evaluate(
() => navigator.serviceWorker.controller !== null,
);
server.serve("b");
await page.evaluate(async () => {
await (await navigator.serviceWorker.getRegistration())?.update();
});
await waitForEvent(page, "update-waiting");
const activation = await page.evaluate(() =>
(globalThis as Probe).__caServiceWorkerTest!.host.requestActivation(),
);
expect(activation).toEqual({ kind: "ACTIVATED_RELOAD_REQUIRED" });
await waitForEvent(page, "reload-required");
return { secondLoad, controlled };
}
test("announces update-waiting and reload-required through the host when build B replaces A", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const server = await startBuildServer(requireBuilds().dist);
try {
await updateFromAToB(page, server);
const registration = await page.evaluate(async () => {
const current = await navigator.serviceWorker.getRegistration();
return {
active: current?.active?.state ?? null,
waiting: current?.waiting ?? null,
};
});
expect(registration).toEqual({ active: "activated", waiting: null });
} finally {
await server.close();
}
});
/** The route chunk of A that B no longer has: `CHANGED_ROUTE_SOURCE`'s. */
async function removedRouteChunk(
dist: ServiceWorkerBuilds["dist"],
): Promise<string> {
const routeChunks = Object.values(
(
JSON.parse(
await readFile(path.join(dist.a, "release-manifest.json"), "utf8"),
) as { routeChunks: Record<string, string> }
).routeChunks,
);
const inB = new Set(await hashedAssets(dist.b));
const removedChunk = routeChunks
.map((chunk) => `/${chunk}`)
.find((chunk) => !inB.has(chunk));
if (!removedChunk) throw new Error("Build B kept every route chunk of A.");
return removedChunk;
}
test("serves A's removed chunk from the previous cache once B controls the page", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const { dist } = requireBuilds();
const removedChunk = await removedRouteChunk(dist);
const server = await startBuildServer(dist);
try {
const { secondLoad, controlled } = await updateFromAToB(page, server);
expect(secondLoad).toEqual({ kind: "ACTIVE", buildId: "sw-e2e-a" });
expect(controlled).toBe(true);
// B's worker now controls the page. The chunk is not in B's manifest and
// not on the server any more, so only A's retained cache can answer.
const fromWorker = await page.evaluate(async (url) => {
const response = await fetch(url);
return { status: response.status, body: await response.text() };
}, removedChunk);
expect(fromWorker).toEqual({
status: 200,
body: await readFile(path.join(dist.a, removedChunk), "utf8"),
});
expect((await page.request.get(`${server.origin}${removedChunk}`)).status())
.toBe(404);
} finally {
await server.close();
}
});
type SameDocumentProbe = typeof globalThis & { __swE2eSameDocument?: boolean };
// 1105/06-03. The old tab's real path, not only `fetch()`: A's page, now
// controlled by B's worker, opens the route whose chunk B removed
// (`CHANGED_ROUTE_SOURCE` is the not-found page, so any unmatched path
// imports it). Under the worker the preload fixture cannot judge preloads
// (the 11-09 allowance above), so this test asserts the outcome: the route
// renders in the same document, the chunk never reaches the server, and the
// strict fixture sees no failure outside the allowance. A worker that cannot
// answer the chunk makes the app's chunk recovery reload into B, which also
// renders the not-found page; only the same-document check tells them apart
// (review 06-R10).
test("opens A's removed route in the old tab without a reload once B controls it", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const { dist } = requireBuilds();
const removedChunk = await removedRouteChunk(dist);
const server = await startBuildServer(dist);
try {
const { controlled } = await updateFromAToB(page, server);
expect(controlled).toBe(true);
const entryScript = () =>
page.evaluate(
() =>
document.querySelector<HTMLScriptElement>('script[type="module"][src]')
?.src ?? null,
);
const entryBefore = await entryScript();
await page.evaluate(() => {
(globalThis as SameDocumentProbe).__swE2eSameDocument = true;
});
const servedBefore = server.served.length;
// A client-side navigation, as a link inside the app makes.
await page.evaluate(() => {
history.pushState({}, "", "/sw-e2e-removed-route");
dispatchEvent(new PopStateEvent("popstate"));
});
await expect(
page.getByRole("heading", { name: /페이지를 찾을 수 없습니다|Page not found/u }),
).toBeVisible({ timeout: 30_000 });
const after = await page.evaluate((chunk) => ({
sameDocument:
(globalThis as SameDocumentProbe).__swE2eSameDocument === true,
chunkRequested:
performance.getEntriesByName(new URL(chunk, location.origin).href)
.length > 0,
}), removedChunk);
expect(after).toEqual({ sameDocument: true, chunkRequested: true });
expect(await entryScript()).toBe(entryBefore);
expect(
server.served.slice(servedBefore).map((response) => response.path),
).not.toContain(removedChunk);
} finally {
await server.close();
}
});
// `beforeAll` already ran `scripts/build-frontend.ts` unmodified (default
// `bundle` config loader); this pins that both builds emitted the worker.
test("builds the ACTIVE worker with the repo's unmodified build script", async () => {
const { dist } = requireBuilds();
for (const root of [dist.a, dist.b]) {
expect(await readdir(root)).toContain("service-worker.js");
}
});