From f6b144cda3a8e20fe1b11aa7fc31e33869848c73 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Tue, 10 Nov 2026 00:46:23 -0800 Subject: [PATCH] test: serve the browser fixtures from a production build Every browser test opens its own page, and each load from the Vite dev server fetched several hundred unbundled modules: a second or two on a CI runner, and a stalled load left the dev client polling for a server it thought lost. The run now builds the fixtures and the app once (tests/fixtures.vite.config.ts, its own vite process so NODE_ENV can be production, about a second) into a temp directory and serves it with vite preview. There is one mode, local and CI alike, and no dev server. The three files that put the app in front of a real backend serve the same build with their proxy through serveBuilt(). Two tests leaned on the dev server. The comment pin test now reads the store from the fixture instead of importing /src from the page, and the replay tests match the recorder's built file name and assert that the saved HTML does not carry that exact URL. Co-Authored-By: Claude Fable 5.2 --- .context/TECHSTACK.md | 15 +- tests/browser.ts | 151 ++++++++++++-------- tests/elementCommentPositionBrowser.test.ts | 4 - tests/fitSelectionBrowser.test.ts | 22 ++- tests/fixtures.vite.config.ts | 28 ++++ tests/fixtures/elementPanel.html | 2 + tests/frameRasterBrowser.test.ts | 3 +- tests/frameReplay.test.ts | 10 +- tests/globalSetup.ts | 7 +- tests/pageControlsBrowser.test.ts | 24 ++-- tests/zoomToolBrowser.test.ts | 22 ++- 11 files changed, 172 insertions(+), 116 deletions(-) create mode 100644 tests/fixtures.vite.config.ts diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index c1ef171d9..304cbe484 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -745,11 +745,16 @@ data-doop-webfonts>` for the roster families the frame names and does not load i - Vitest 5 - unit/integration tests across `server/` and `src/`; run via `bun run test` (`vitest run`). Tests live in `tests/`. -- Browser tests drive one shared Chromium and one Vite fixture server (`tests/browser.ts`), which - `tests/globalSetup.ts` starts and warms (every `tests/fixtures/*.html` loaded once) before any - worker runs; a file calls `openBrowser()` for its own context (focus emulated, 30s navigation - bound) and `fixtureUrl()` for its page. A test that needs its own Vite server (a proxy) builds it - from `fixtureServerConfig()`, so every server shares one dependency hash and cache directory. +- Browser tests drive one shared Chromium and one fixture server (`tests/browser.ts`), which + `tests/globalSetup.ts` starts before any worker runs. The server hands out a production build: + `tests/fixtures.vite.config.ts` is the app's own build with every `tests/fixtures/*.html` as an + entry beside `index.html`, built once per run (about a second, as its own `vite build` process + with `NODE_ENV=production`) into a temp directory and served by `vite preview`; there is no dev + server and no live-reload client. A file calls `pagePerTest()` for a page per test in its own + context (focus emulated, 30s navigation bound) and `fixtureUrl()` for its page. A fixture + exposes what a test needs on `window`; a test cannot import `/src/...` from the page. A test that + puts the app in front of a real backend starts its own server over the same build with + `serveBuilt(proxy)`. - CI runs the browser tests on the Chrome for Testing build named in `.chrome-version`, installed by the `test` job and passed as `CHROME_PATH`, so a runner image update cannot change the browser without a commit. `bun run test:linux [vitest args]` (`scripts/test-linux.sh`, diff --git a/tests/browser.ts b/tests/browser.ts index 30318058a..a8c801484 100644 --- a/tests/browser.ts +++ b/tests/browser.ts @@ -1,29 +1,36 @@ -import { readdirSync } from 'node:fs' +import { execFile } from 'node:child_process' +import { cpSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { promisify } from 'node:util' import puppeteer, { type Browser, type Page, type Permission } from 'puppeteer-core' -import { createServer, type InlineConfig, type ServerOptions } from 'vite' +import { preview, type ProxyOptions } from 'vite' import { afterAll, afterEach, beforeAll, expect, inject } from 'vitest' import { findBrowserPath, launchBrowser } from '../server/screenshot.ts' /** * Shared rig for the tests that drive a real Chromium: ONE browser and ONE - * Vite server for the fixtures, started and warmed by tests/globalSetup.ts - * before any worker runs. + * server for the fixtures, started by tests/globalSetup.ts before any worker + * runs. * - * Every file used to launch its own Chromium and its own Vite server. On the - * 2-vCPU CI runner that meant a cold Chrome start (30s+ on a fresh VM, past - * puppeteer's launch timeout) and a cold transform of the whole app (past the - * 5-10s navigation timeouts) inside the first files' hooks, and files whose - * servers asked for different `optimizeDeps` rewrote the shared dependency - * cache under each other. Now the cold costs are paid once, outside any test - * timeout, and each file gets a fresh browser context (its own cookies and - * storage, and its own window, so its pages stay visible and focused) on the - * warm browser. + * The server hands out a production build of the fixtures (and of the app's + * own index.html), made once per run by tests/fixtures.vite.config.ts. A page + * is a few bundled files, so a load costs much the same on a 2-vCPU CI runner + * as it does here, and it is the code that ships. A dev server would serve + * the app as hundreds of unbundled modules, a second or two per load on CI, + * and its live-reload client gives a stalled load up for a lost server and + * never recovers the page. + * + * Chrome's cold start (30s+ on a fresh VM, past puppeteer's launch timeout) + * and the build are paid once, outside any test timeout, and each file gets a + * fresh browser context (its own cookies and storage, and its own window, so + * its pages stay visible and focused) on the warm browser. */ declare module 'vitest' { interface ProvidedContext { /** null when no Chromium is installed; every browser test skips then */ - browserRig: { wsEndpoint: string; fixtureOrigin: string } | null + browserRig: { wsEndpoint: string; fixtureOrigin: string; builtDir: string } | null } } @@ -33,10 +40,10 @@ const FIXTURES = 'tests/fixtures' * caches from a cold disk; that has taken well over puppeteer's 30s. */ const COLD_START_MS = 180_000 -/** A fixture load fetches and runs the app as hundreds of unbundled modules: - * well under a second here, several on a busy 2-vCPU runner. Files set a - * tight default timeout for their UI waits (5s), which puppeteer would also - * apply to navigation; loads get their own, roomier bound. */ +/** A fixture load is a handful of bundled files, well under a second. Files + * set a tight default timeout for their UI waits (5s), which puppeteer would + * also apply to navigation; loads get their own, roomier bound for a runner + * that stalls. */ const NAVIGATION_TIMEOUT_MS = 30_000 /** The bound on one UI wait (waitForSelector, waitForFunction, a locator @@ -47,54 +54,87 @@ const NAVIGATION_TIMEOUT_MS = 30_000 const STEP_TIMEOUT_MS = 15_000 /** - * The Vite config every fixture server uses. One `optimizeDeps` for all of - * them: the dependency hash covers `include`, and a server whose hash differs - * re-bundles the cache directory out from under the others. The fixtures are - * scan entries so their dependencies are bundled up front instead of being - * discovered mid-test, which reloads every open page. The cache directory is - * separate from `bun run dev`'s, so a dev server in the same checkout never - * fights a test run over it, and nothing is watched: a file written while the - * suite runs must not reload the pages under test. + * Build every fixture and the app into a fresh directory outside the tree. + * Vite runs as its own process because a production build is decided by + * NODE_ENV, which vitest has already set to `test` in this one. What the + * fixtures fetch by path at run time (a stylesheet, an image) is not part of + * the bundle, so those files are copied next to the built pages. */ -export function fixtureServerConfig(server: ServerOptions = {}): InlineConfig { - return { +async function buildFixtures(): Promise { + const dir = mkdtempSync(path.join(tmpdir(), 'doop-test-fixtures-')) + try { + await promisify(execFile)( + process.execPath, + ['node_modules/vite/bin/vite.js', 'build', '--config', 'tests/fixtures.vite.config.ts', '--outDir', dir], + { env: { ...process.env, NODE_ENV: 'production' } }, + ) + cpSync(FIXTURES, path.join(dir, FIXTURES), { + recursive: true, + filter: (source) => !/\.(html|ts)$/.test(source), + }) + return dir + } catch (error) { + rmSync(dir, { recursive: true, force: true }) + throw error + } +} + +export interface BuiltServer { + /** without a trailing slash */ + origin: string + close(): Promise +} + +/** + * Serve the built pages. The shared fixture server answers only the files + * that exist. A test that puts the app in front of a real backend starts its + * own with `proxy`, and that one also answers every app route with + * index.html, as the production server does. + */ +export async function serveBuilt( + proxy?: Record, + builtDir = rig().builtDir, +): Promise { + const server = await preview({ + configFile: false, logLevel: 'error', - cacheDir: 'node_modules/.vite-test', - optimizeDeps: { - entries: ['index.html', `${FIXTURES}/*.html`], - include: ['posthog-js/dist/posthog-recorder', 'posthog-js/dist/rrweb'], - }, - server: { port: 0, watch: null, ...server }, + appType: proxy ? 'spa' : 'mpa', + build: { outDir: builtDir }, + preview: { port: 0, proxy }, + }) + return { + origin: server.resolvedUrls!.local[0]!.replace(/\/$/, ''), + close: () => server.close(), } } export interface BrowserRig { wsEndpoint: string fixtureOrigin: string + builtDir: string close(): Promise } -/** Launch the browser and the fixture server, then load every fixture once so - * dependency bundling and the app's transforms are done before tests start. */ +/** Launch the browser and build and serve the fixtures, then load one page so + * the browser's first render is behind it before tests start. */ export async function startBrowserRig(): Promise { if (!findBrowserPath()) return null - const [launched, created] = await Promise.allSettled([ - launchBrowser(COLD_START_MS), - createServer(fixtureServerConfig()), - ]) + const [launched, built] = await Promise.allSettled([launchBrowser(COLD_START_MS), buildFixtures()]) const browser = launched.status === 'fulfilled' ? launched.value : null - const vite = created.status === 'fulfilled' ? created.value : null + const builtDir = built.status === 'fulfilled' ? built.value : null + let server: BuiltServer | null = null const close = async () => { await browser?.close() - await vite?.close() + await server?.close() + if (builtDir) rmSync(builtDir, { recursive: true, force: true }) } try { - if (!browser || !vite) - throw launched.status === 'rejected' ? launched.reason : (created as PromiseRejectedResult).reason - await vite.listen() - const fixtureOrigin = vite.resolvedUrls!.local[0]! - await warmFixtures(browser, fixtureOrigin) - return { wsEndpoint: browser.wsEndpoint(), fixtureOrigin, close } + if (!browser || !builtDir) + throw launched.status === 'rejected' ? launched.reason : (built as PromiseRejectedResult).reason + server = await serveBuilt(undefined, builtDir) + const fixtureOrigin = `${server.origin}/` + await warmBrowser(browser, fixtureOrigin) + return { wsEndpoint: browser.wsEndpoint(), fixtureOrigin, builtDir, close } } catch (error) { /* a half-started rig must not leave a Chromium or a server holding the run open */ await close() @@ -102,16 +142,13 @@ export async function startBrowserRig(): Promise { } } -async function warmFixtures(browser: Browser, origin: string): Promise { +/** A fresh Chrome's first page starts a renderer and fills its font and code + * caches; one load here keeps that out of the first test's timeout. */ +async function warmBrowser(browser: Browser, origin: string): Promise { const context = await browser.createBrowserContext() try { - /* one at a time: the first pays for the dependency bundle, the rest only - for the modules that are theirs */ - for (const file of readdirSync(FIXTURES).filter((name) => name.endsWith('.html'))) { - const page = await context.newPage() - await page.goto(`${origin}${FIXTURES}/${file}`, { waitUntil: 'load', timeout: COLD_START_MS }) - await page.close() - } + const page = await context.newPage() + await page.goto(`${origin}${FIXTURES}/drawing.html`, { waitUntil: 'load', timeout: COLD_START_MS }) } finally { await context.close() } @@ -126,7 +163,7 @@ export interface TestBrowser { close(): Promise } -function rig(): { wsEndpoint: string; fixtureOrigin: string } { +function rig(): { wsEndpoint: string; fixtureOrigin: string; builtDir: string } { const provided = inject('browserRig') if (!provided) throw new Error('no browser rig: tests/globalSetup.ts found no Chromium') return provided diff --git a/tests/elementCommentPositionBrowser.test.ts b/tests/elementCommentPositionBrowser.test.ts index 66fb87878..7b3f6ff18 100644 --- a/tests/elementCommentPositionBrowser.test.ts +++ b/tests/elementCommentPositionBrowser.test.ts @@ -48,10 +48,6 @@ describe.skipIf(!findBrowserPath())('element comment pin placement', () => { page = await pages.open() page.on('pageerror', (error) => errors.push(String(error))) await page.goto(fixtureUrl('elementPanel.html')) - await page.addScriptTag({ - type: 'module', - content: "import { useStore } from '/src/lib/store.ts'; window.commentPositionStore = useStore", - }) await page.waitForFunction(() => !!window.commentPositionStore) await page.evaluate( ({ frame, comment }) => { diff --git a/tests/fitSelectionBrowser.test.ts b/tests/fitSelectionBrowser.test.ts index c503b06d5..459f61658 100644 --- a/tests/fitSelectionBrowser.test.ts +++ b/tests/fitSelectionBrowser.test.ts @@ -1,14 +1,13 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' -import { createServer, type ViteDevServer } from 'vite' import type { Page } from 'puppeteer-core' import { findBrowserPath } from '../server/screenshot' -import { fixtureServerConfig, pagePerTest } from './browser' +import { pagePerTest, serveBuilt, type BuiltServer } from './browser' import { freePort, startServer, type Server } from './harness' /* ⇧2 fits the selection into the part of the stage the panels leave open, not the whole window under them */ describe.skipIf(!findBrowserPath())('zoom to selection with the panels open', () => { - let vite: ViteDevServer + let web: BuiltServer let server: Server const pages = pagePerTest() let page: Page @@ -20,16 +19,11 @@ describe.skipIf(!findBrowserPath())('zoom to selection with the panels open', () let frameId: string beforeAll(async () => { const port = await freePort() - vite = await createServer( - fixtureServerConfig({ - proxy: { - '/api': { target: `http://localhost:${port}` }, - '/ws': { target: `ws://localhost:${port}`, ws: true }, - }, - }), - ) - await vite.listen() - origin = vite.resolvedUrls!.local[0]!.replace(/\/$/, '') + web = await serveBuilt({ + '/api': { target: `http://localhost:${port}` }, + '/ws': { target: `ws://localhost:${port}`, ws: true }, + }) + origin = web.origin server = await startServer({ PORT: String(port), BETTER_AUTH_URL: origin }) }, 60_000) beforeEach(async () => { @@ -67,7 +61,7 @@ describe.skipIf(!findBrowserPath())('zoom to selection with the panels open', () await page.waitForSelector('[data-frame-title]') }) afterAll(async () => { - await vite?.close() + await web?.close() server?.stop() }) diff --git a/tests/fixtures.vite.config.ts b/tests/fixtures.vite.config.ts new file mode 100644 index 000000000..32a1f6129 --- /dev/null +++ b/tests/fixtures.vite.config.ts @@ -0,0 +1,28 @@ +import { readdirSync } from 'node:fs' +import { mergeConfig, type UserConfig } from 'vite' +import app from '../vite.config.ts' + +/* The production build the browser tests load (tests/browser.ts runs it once + per test run): the app's own build with every fixture page as an entry + beside index.html, minified as it ships. No .env file is read, so the pages + are the same on every machine, and no source maps are written: nothing + reads them, and the build stays about a second. */ +const pages: UserConfig = { + logLevel: 'error', + envDir: false, + build: { + emptyOutDir: true, + sourcemap: false, + reportCompressedSize: false, + rollupOptions: { + input: [ + 'index.html', + ...readdirSync('tests/fixtures') + .filter((name) => name.endsWith('.html')) + .map((name) => `tests/fixtures/${name}`), + ], + }, + }, +} + +export default mergeConfig(app as UserConfig, pages) diff --git a/tests/fixtures/elementPanel.html b/tests/fixtures/elementPanel.html index 61d863ee5..7b703ffd0 100644 --- a/tests/fixtures/elementPanel.html +++ b/tests/fixtures/elementPanel.html @@ -19,6 +19,8 @@ import { editElementGeometry } from '/src/lib/frameBridge.ts' import { nudgeSelection } from '/src/lib/layerEdits.ts' import '/src/styles.css' + /* the app's own store, for a test that seeds state the harness has no call for */ + window.commentPositionStore = useStore window.elementPanelHarness = { /* one frame, or several stacked in order (later ones on top) */ seed: (frame) => { diff --git a/tests/frameRasterBrowser.test.ts b/tests/frameRasterBrowser.test.ts index 2a248c785..ec29add19 100644 --- a/tests/frameRasterBrowser.test.ts +++ b/tests/frameRasterBrowser.test.ts @@ -144,8 +144,7 @@ describe.skipIf(!findBrowserPath())('rasterizing a frame in the browser', () => }) it('rejects a frame with an image the browser cannot fetch, for the server to render', async () => { - /* a host nothing answers on; the fixture server itself answers any - path with the app page */ + /* a host nothing answers on */ const failed = await page.evaluate(() => (window as unknown as { render: (o: unknown) => Promise }) .render({ html: '' }) diff --git a/tests/frameReplay.test.ts b/tests/frameReplay.test.ts index f1039ac27..55c0f30df 100644 --- a/tests/frameReplay.test.ts +++ b/tests/frameReplay.test.ts @@ -29,6 +29,10 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => { }) }, 60_000) + /** The recorder the frame downloads: its own file in the build, named + * recorder-.js (the page's posthog-recorder chunk is another file). */ + const isRecorder = (request: HTTPRequest) => /\/recorder-[\w-]+\.js$/.test(new URL(request.url()).pathname) + async function render(html: string, index = 0) { await page.evaluate( (html, index) => { @@ -59,7 +63,7 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => { }) let attempts = 0 const onRequest = (request: HTTPRequest) => { - if (new URL(request.url()).pathname.endsWith('/dist/recorder.js')) { + if (isRecorder(request)) { attempts++ if (attempts === 1) void request.abort('failed') else release(request) @@ -92,7 +96,7 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => { const saved = await page.evaluate(() => window.messages.find((m) => m.type === 'doop:edited')!.html) expect(saved).toContain('
Preserve design content
') expect(saved).toContain('') - expect(saved).not.toContain('/dist/recorder.js') + expect(saved).not.toContain(new URL(request.url()).pathname) await page.evaluate(() => { window.messages = window.messages.filter((m) => m.type !== 'doop:edited') }) @@ -179,7 +183,7 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => { await page.setRequestInterception(true) let attempts = 0 const onRequest = (request: HTTPRequest) => { - if (new URL(request.url()).pathname.endsWith('/dist/recorder.js')) { + if (isRecorder(request)) { attempts++ void request.abort('failed') } else void request.continue() diff --git a/tests/globalSetup.ts b/tests/globalSetup.ts index 7328645e5..224a0d52d 100644 --- a/tests/globalSetup.ts +++ b/tests/globalSetup.ts @@ -8,7 +8,7 @@ import { buildTemplate } from './harness.ts' /* Runs once per vitest invocation, before any worker: the migrated PGlite template every integration server is copied from (its own temp directory, so overlapping runs in one checkout never see each other's files), and the - shared, warmed Chromium + fixture server the browser tests drive. */ + shared Chromium and the built fixtures' server the browser tests drive. */ let dir: string let rig: BrowserRig | null = null @@ -17,7 +17,10 @@ export async function setup(project: TestProject): Promise { const [, started] = await Promise.all([buildTemplate(dir), startBrowserRig()]) rig = started project.provide('templateDir', dir) - project.provide('browserRig', rig && { wsEndpoint: rig.wsEndpoint, fixtureOrigin: rig.fixtureOrigin }) + project.provide( + 'browserRig', + rig && { wsEndpoint: rig.wsEndpoint, fixtureOrigin: rig.fixtureOrigin, builtDir: rig.builtDir }, + ) } export async function teardown(): Promise { diff --git a/tests/pageControlsBrowser.test.ts b/tests/pageControlsBrowser.test.ts index a68a07d5c..f26caa5e9 100644 --- a/tests/pageControlsBrowser.test.ts +++ b/tests/pageControlsBrowser.test.ts @@ -1,12 +1,11 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' -import { createServer, type ViteDevServer } from 'vite' import type { Page } from 'puppeteer-core' import { findBrowserPath } from '../server/screenshot' -import { fixtureServerConfig, pagePerTest } from './browser' +import { pagePerTest, serveBuilt, type BuiltServer } from './browser' import { freePort, startServer, type Server } from './harness' describe.skipIf(!findBrowserPath())('page list controls and keyboard history', () => { - let vite: ViteDevServer + let web: BuiltServer let server: Server const pages = pagePerTest() let page: Page @@ -14,19 +13,14 @@ describe.skipIf(!findBrowserPath())('page list controls and keyboard history', ( /* every test signs up as someone new, so each works on a canvas of its own */ let accounts = 0 beforeAll(async () => { - /* vite needs the server's port for its proxy and the server needs vite's + /* the web server needs the backend's port for its proxy and the backend needs its origin as BETTER_AUTH_URL, so the port is picked before either starts */ const port = await freePort() - vite = await createServer( - fixtureServerConfig({ - proxy: { - '/api': { target: `http://localhost:${port}` }, - '/ws': { target: `ws://localhost:${port}`, ws: true }, - }, - }), - ) - await vite.listen() - origin = vite.resolvedUrls!.local[0]!.replace(/\/$/, '') + web = await serveBuilt({ + '/api': { target: `http://localhost:${port}` }, + '/ws': { target: `ws://localhost:${port}`, ws: true }, + }) + origin = web.origin server = await startServer({ PORT: String(port), BETTER_AUTH_URL: origin }) }, 60_000) beforeEach(async () => { @@ -57,7 +51,7 @@ describe.skipIf(!findBrowserPath())('page list controls and keyboard history', ( await page.waitForSelector('[data-page-id]') }, 60_000) afterAll(async () => { - await vite?.close() + await web?.close() server?.stop() }) diff --git a/tests/zoomToolBrowser.test.ts b/tests/zoomToolBrowser.test.ts index 2637fac37..b63bee32a 100644 --- a/tests/zoomToolBrowser.test.ts +++ b/tests/zoomToolBrowser.test.ts @@ -1,15 +1,14 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' -import { createServer, type ViteDevServer } from 'vite' import type { Page } from 'puppeteer-core' import { findBrowserPath } from '../server/screenshot' -import { fixtureServerConfig, pagePerTest } from './browser' +import { pagePerTest, serveBuilt, type BuiltServer } from './browser' import { freePort, startServer, type Server } from './harness' /* Z held is the Zoom tool: a click zooms in, a drag zooms onto its box, Esc drops the box, and letting go of Z returns to the tool before it, in whichever order Z and the mouse are released */ describe.skipIf(!findBrowserPath())('the Zoom tool', () => { - let vite: ViteDevServer + let web: BuiltServer let server: Server const pages = pagePerTest() let page: Page @@ -17,20 +16,15 @@ describe.skipIf(!findBrowserPath())('the Zoom tool', () => { let users = 0 beforeAll(async () => { const port = await freePort() - vite = await createServer( - fixtureServerConfig({ - proxy: { - '/api': { target: `http://localhost:${port}` }, - '/ws': { target: `ws://localhost:${port}`, ws: true }, - }, - }), - ) - await vite.listen() - origin = vite.resolvedUrls!.local[0]!.replace(/\/$/, '') + web = await serveBuilt({ + '/api': { target: `http://localhost:${port}` }, + '/ws': { target: `ws://localhost:${port}`, ws: true }, + }) + origin = web.origin server = await startServer({ PORT: String(port), BETTER_AUTH_URL: origin }) }, 60_000) afterAll(async () => { - await vite?.close() + await web?.close() server?.stop() }) /* each test signs up its own person and draws on their own canvas */