diff --git a/docs/output.md b/docs/output.md index 6171fdc..f552b69 100644 --- a/docs/output.md +++ b/docs/output.md @@ -310,7 +310,7 @@ pulls a route), scores rounded down to four decimals (so a shot that differs nev "results": [ { "url": "/about", "left": "/about", "right": "/about", // a pair: "/a::/b", "/a", "/b" - "selector": null, "hook": false, // hook: a before hook ran + "selector": null, "hook": false, // hook: a before or beforeShot hook ran "width": 1440, "status": "compared", "score": 0.9714, // share of measured pixels that match "alignedScore": 1, // score over the aligned rows; null unless there are bands diff --git a/docs/scoping.md b/docs/scoping.md index 865c2dd..f3b0063 100644 --- a/docs/scoping.md +++ b/docs/scoping.md @@ -68,8 +68,10 @@ it, with the clock and seeded `Math.random` already in force: export default { routes: [ { left: "/", before: async (page) => { await page.click("[aria-label=Menu]"); } }, + { left: "/docs", beforeShot: async (page) => { await page.click("[data-tab=intro]"); } }, ], - // For every route without its own `before` (which replaces it), CLI routes included. + // For every route without its own `before` (which replaces it), CLI routes included; + // a top-level `beforeShot` works the same way. before: async (page, { side, route, width }) => { const accept = page.getByRole("button", { name: "Accept" }); if (await accept.isVisible()) await accept.click(); @@ -80,10 +82,17 @@ export default { `side` is `"left"` or `"right"`, `route` the route's name (`/a` or `/a::/b`), `width` the viewport width. Use `side` only where the markup legitimately differs (the button has a different selector on each side), never to make the sides look alike. A hook that throws -is a route error, `before hook failed on left: …`, and isn't retried. A route that ran one -has `"hook": true` in `results.json` and a `before hook` badge on its report card. +is a route error, `before hook failed on left: …` (or `beforeShot …`), and isn't retried. +A route that ran one has `"hook": true` in `results.json` and a `hook` badge on its report +card. Actions in a hook use Playwright's 30s default timeout, so check before clicking what may -not be there (as above); `hideSelectors` and `extraCss` apply after the hook. +not be there (as above); `hideSelectors` and `extraCss` apply after `before` and before `beforeShot`. + +The settle scrolls the whole page to load lazy content, so a state the scroll changes (a +scroll-spy nav, a container re-measured on scroll) doesn't survive a `before` hook. Set it in +a `beforeShot` hook instead: same signature, but it runs after the settle, right before masks +and the shot. renderdiff doesn't settle again after it, so await whatever it changes. On a +`selector` route the element is still scrolled into view after it. ## Signed-in pages diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 49fd38b..20c58c4 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -123,8 +123,8 @@ Report (`--open`, for a human): green from 99.5%, amber to 97%, red below. | `page is Npx tall at Wpx wide, past the …px sanity ceiling …` | Taller than 57,600,000px ÷ width (never under 40,000px): a runaway layout, not a page. | | `selector "…" matched N elements on left (/a), expected 1` | Make it unique (an id, `data-test`, `>> nth=0`), or list the route once per element. | | `selector "…" has no box on …` / `is off the page on …` | Matched an element not rendered (`display: none`, zero size) or outside the page. | -| `before hook failed on left: …` | The hook threw. Never retried. | -| `timeout after 120s at settle on left` | That side never finished the step (`load`, `before hook`, `settle`, `screenshot`): a hung script, a dead renderer, a hook that never resolves. Retried once in a fresh page, except a hung hook. For a page that is just very slow, raise `RENDERDIFF_SHOT_TIMEOUT` (seconds). | +| `before hook failed on left: …` | The hook threw (`beforeShot hook failed …` for that hook). Never retried. | +| `timeout after 120s at settle on left` | That side never finished the step (`load`, `before hook`, `settle`, `beforeShot hook`, `screenshot`): a hung script, a dead renderer, a hook that never resolves. Retried once in a fresh page, except a hung hook. For a page that is just very slow, raise `RENDERDIFF_SHOT_TIMEOUT` (seconds). | A failed `--computed` snapshot (`snapshot failed on /a@1440 (…)` on the `computed:` line) is not a route error: the pixel result stands. @@ -258,6 +258,8 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so banner *both* sides show, sign in, set a carousel to slide 1 on both. Not: branching on `side` to make the sides look alike, hiding or removing an element on one side. `side` is for markup that legitimately differs. Say in the verdict that a hook ran (`hook: true`). + `beforeShot` (same forms) runs after settle, right before masks and the shot: for state the + settle's scroll pass changes, e.g. a scroll-spy nav. Nothing settles after it, so await it. - **Signed-in pages:** `npx playwright codegen --save-storage=auth.json `, then `--storage-state auth.json` (or `--left-storage-state`/`--right-storage-state`, or config `storageState`, relative to the config file). The file holds live session tokens: never @@ -287,7 +289,7 @@ export default { A mask takes exactly one of `selector` or `locate: (page) => Locator`; without `urlPath` it applies to every route, and on a pair it matches either side's path. `--mask ` adds to the config's masks. Also: `threshold`, `outDir`, `concurrency`, `extraCss`, `before`, -`storageState`. `hideSelectors`: match the element **exactly** (consent scripts stamp classes on +`beforeShot`, `storageState`. `hideSelectors`: match the element **exactly** (consent scripts stamp classes on ``; a loose selector blanks the whole document and blank matches blank), and they hide rather than remove. diff --git a/src/cache.ts b/src/cache.ts index 8556f84..0755399 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -10,7 +10,12 @@ export const REPLAY_TTL = 60 * 60_000; /** A shot's identity in a recording: what decides which requests its load makes. */ export const shotId = (route: Route, width: number) => - JSON.stringify([route.right, width, route.before && String(route.before)]); + JSON.stringify([ + route.right, + width, + route.before && String(route.before), + route.beforeShot && String(route.beforeShot), + ]); /** Everything that changes what the right origin serves, so one recording never answers another. */ export function cacheFile(cfg: ResolvedConfig, browser: { name: string; version: string }): string { diff --git a/src/capture.ts b/src/capture.ts index 7b167cc..e0e6a19 100644 --- a/src/capture.ts +++ b/src/capture.ts @@ -99,7 +99,7 @@ async function networkIdle(page: Page, quiet: number, timeout: number): Promise< while (Date.now() < end && (net.open.size || Date.now() - net.last < quiet)) await sleep(25); } -/** A `before` hook threw. Never retried: the hook may have half-run against the page. */ +/** A `before` or `beforeShot` hook threw. Never retried: the hook may have half-run against the page. */ export class HookError extends Error {} /** @@ -201,16 +201,19 @@ export async function capture( const type = res.headers()["content-type"]!.split(";")[0]!.trim(); throw new Error(`not an HTML page: server sent ${type} at ${url}`); } - if (route.before) { - step.set(page, "before hook"); + const hook = async (name: "before" | "beforeShot") => { + const fn = route[name]; + if (!fn) return; + step.set(page, `${name} hook`); try { - await route.before(page, { side, route: label(route), width }); + await fn(page, { side, route: label(route), width }); } catch (e) { throw new HookError( - `before hook failed on ${side}: ${e instanceof Error ? e.message : String(e)}`, + `${name} hook failed on ${side}: ${e instanceof Error ? e.message : String(e)}`, ); } - } + }; + await hook("before"); step.set(page, "settle"); await page.addStyleTag({ content: cfg.neutralizeCss }); // Before the scroll too, so autoplay never starts and page state driven by playback stays put. @@ -253,6 +256,8 @@ export async function capture( if (cfg.freezeVideo) await page.evaluate(freezeVideo); const failed = [...new Set([...network.get(page)!.failed, ...fonts])]; await page.addStyleTag({ content: cfg.neutralizeCss }); // anything injected late + await hook("beforeShot"); + step.set(page, "settle"); const selector = route.selector?.[side]; const where = `on ${side} (${route[side]})`; diff --git a/src/cli.ts b/src/cli.ts index e77c04a..c69baa4 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -193,7 +193,8 @@ const HELP = ` With --storage-state, each side starts with that Playwright storage state (cookies, localStorage), e.g. signed in. Make one with: npx playwright codegen --save-storage=auth.json - A before hook in the config runs on each page before it is shot, e.g. to open a menu. + A before hook in the config runs on each page before it settles, e.g. to open a menu; + a beforeShot hook runs after, right before the shot. --accept "" records this run's differences in renderdiff.accepted.json (next to the config, or in cwd); later runs report them as accepted, and anything new still shows. @@ -347,6 +348,7 @@ async function sitemapRoutes(spec: string | true, routes: Route[]): Promise !covered.has(p)), args.selector, fileConfig.before, + fileConfig.beforeShot, ); } @@ -423,7 +425,7 @@ if (!rawRoutes.length && !args.sitemap) { let routes: Route[]; try { - routes = parseRoutes(rawRoutes, args.selector, fileConfig.before); + routes = parseRoutes(rawRoutes, args.selector, fileConfig.before, fileConfig.beforeShot); } catch (e) { die(e instanceof Error ? e.message : String(e)); } diff --git a/src/config.ts b/src/config.ts index d9e5a14..d31bc59 100644 --- a/src/config.ts +++ b/src/config.ts @@ -24,11 +24,13 @@ export interface Route { right: string; selector: Sides | null; before: Hook | null; + beforeShot: Hook | null; } /** - * Runs on each side after the page loads and before it settles and is shot, e.g. to open a - * menu. `route` is the route's name (`/a`, or `/a::/b` for a pair), the same on both sides. + * Runs on each side, e.g. to open a menu: `before` after the page loads, before it settles; + * `beforeShot` after it settles, right before masks and the shot. `route` is the route's name + * (`/a`, or `/a::/b` for a pair), the same on both sides. */ export type Hook = ( page: Page, @@ -41,7 +43,7 @@ export type Hook = ( */ export type RouteSpec = | string - | { left: string; right?: string; selector?: string | Sides; before?: Hook }; + | { left: string; right?: string; selector?: string | Sides; before?: Hook; beforeShot?: Hook }; /** `pricing` / `/pricing/` -> `/pricing`; `/` stays `/`. */ export const normalize = (url: string) => { @@ -64,9 +66,14 @@ export const name = (r: Pick) => * Specs -> normalized, deduplicated routes; throws on an empty side or a glob. A string is a * pair when it has a `::` followed by `/` (or ending it, so `/a::` is an empty side, not a * literal), which keeps `?q=std::vector` and `/wiki/Talk:Foo` single routes. A CLI - * `selector` replaces every route's own; a route's own `before` replaces the top-level one. + * `selector` replaces every route's own; a route's own `before` (or `beforeShot`) replaces the top-level one. */ -export function parseRoutes(specs: RouteSpec[], selector?: Sides, before?: Hook): Route[] { +export function parseRoutes( + specs: RouteSpec[], + selector?: Sides, + before?: Hook, + beforeShot?: Hook, +): Route[] { const out = new Map(); for (const spec of specs) { let sides: [string, string]; @@ -90,18 +97,20 @@ export function parseRoutes(specs: RouteSpec[], selector?: Sides, before?: Hook) right: normalize(sides[1]), selector: selector ?? (typeof own === "string" ? { left: own, right: own } : (own ?? null)), before: (typeof spec === "string" ? undefined : spec.before) ?? before ?? null, + beforeShot: (typeof spec === "string" ? undefined : spec.beforeShot) ?? beforeShot ?? null, }; const same = out.get(name(route)); - // JSON drops a function but keeps a null, so `before` is compared on its own below. + // JSON drops a function but keeps a null, so hooks are compared on their own below. if ( same && - JSON.stringify({ ...same, before: 0 }) !== JSON.stringify({ ...route, before: 0 }) + JSON.stringify({ ...same, before: 0, beforeShot: 0 }) !== + JSON.stringify({ ...route, before: 0, beforeShot: 0 }) ) { throw new Error(`two routes both read as ${name(route)}; change one of their selectors`); } - if (same && same.before !== route.before) { + if (same && (same.before !== route.before || same.beforeShot !== route.beforeShot)) { throw new Error( - `two routes both read as ${name(route)}; they have different before hooks — merge them into one route`, + `two routes both read as ${name(route)}; they have different hooks — merge them into one route`, ); } out.set(name(route), route); @@ -237,10 +246,12 @@ export interface RenderdiffConfig { left?: string; /** Right origin, e.g. `https://example.com`. A trailing slash is stripped. */ right?: string; - /** Routes to diff when none are passed on the command line. A route object may take a `selector` and a `before`. */ + /** Routes to diff when none are passed on the command line. A route object may take a `selector`, `before` and `beforeShot`. */ routes?: RouteSpec[]; /** A {@link Hook} for every route without its own `before`, CLI routes included. */ before?: Hook; + /** A {@link Hook} for every route without its own `beforeShot`, CLI routes included. */ + beforeShot?: Hook; /** * Playwright storage state files (cookies, localStorage) to start each side with, e.g. to be * signed in. One path for both sides, or per side. Relative to the config file. @@ -394,6 +405,7 @@ function validate(c: Record, file: string) { } const hook = "a function (page, { side, route, width }) => Promise"; if (c.before !== undefined && typeof c.before !== "function") bad("before", hook); + if (c.beforeShot !== undefined && typeof c.beforeShot !== "function") bad("beforeShot", hook); const s = c.storageState as Record | undefined; if ( s !== undefined && @@ -414,18 +426,23 @@ function validate(c: Record, file: string) { (c.routes as unknown[]).forEach((r, i) => { if (typeof r === "string") return; if (typeof r !== "object" || r === null || Array.isArray(r)) { - bad(`routes[${i}]`, "a string or an object { left, right?, selector?, before? }"); + bad( + `routes[${i}]`, + "a string or an object { left, right?, selector?, before?, beforeShot? }", + ); } const o = r as Record; for (const key of Object.keys(o)) { - if (!["left", "right", "selector", "before"].includes(key)) { + if (!["left", "right", "selector", "before", "beforeShot"].includes(key)) { throw new Error( - `${file}: \`routes[${i}].${key}\` is not a route key (left, right, selector, before)`, + `${file}: \`routes[${i}].${key}\` is not a route key (left, right, selector, before, beforeShot)`, ); } } if (o.before !== undefined && typeof o.before !== "function") bad(`routes[${i}].before`, hook); + if (o.beforeShot !== undefined && typeof o.beforeShot !== "function") + bad(`routes[${i}].beforeShot`, hook); const sel = o.selector as Record | undefined; if ( sel !== undefined && diff --git a/src/report.ts b/src/report.ts index a7dbfb4..7e7b742 100644 --- a/src/report.ts +++ b/src/report.ts @@ -33,7 +33,7 @@ interface BaseResult { right: string; /** The element compared on each side; null for the whole page. */ selector: Sides | null; - /** A `before` hook ran on both sides before the shot, so the page was measured in its state. */ + /** A `before` or `beforeShot` hook ran on both sides before the shot, so the page was measured in its state. */ hook: boolean; width: number; } @@ -424,7 +424,7 @@ const head = (r: ComparedResult) => ` ${pct(r.score)} ${esc(name(r))} @${r.width}px - ${r.hook ? `before hook` : ""} + ${r.hook ? `hook` : ""} ${r.accepted ? `accepted: ${esc(reasons(r))}` : ""} ${r.heightDelta ? `height ${signed(r.heightDelta)}px` : ""} ${r.widthDelta ? `width ${signed(r.widthDelta)}px` : ""} diff --git a/src/run.ts b/src/run.ts index f57d247..50ca74e 100644 --- a/src/run.ts +++ b/src/run.ts @@ -313,8 +313,13 @@ export async function run({ for (let job = queue.shift(); job; job = queue.shift()) { const { route, width } = job; const key = name(route); - const { before, ...where } = route; - const entry = { url: label(route), ...where, hook: before !== null, width }; + const { before, beforeShot, ...where } = route; + const entry = { + url: label(route), + ...where, + hook: before !== null || beforeShot !== null, + width, + }; const tag = `${label(route)} @${width}`; // Its own line: parse.ts reads the route on the row as one \S+ token. const sel = route.selector ? `selector ${selectorText(route.selector)}` : ""; @@ -733,7 +738,7 @@ async function shoot( await page.close(); pages[side] = await page.context().newPage(); await prepare(pages[side], cfg, now); - const E = at === "before hook" ? HookError : errors.TimeoutError; + const E = at === "before hook" || at === "beforeShot hook" ? HookError : errors.TimeoutError; throw new E(`timeout after ${SHOT_TIMEOUT / 1000}s at ${at} on ${side}`); }; try { diff --git a/tests/fixtures/pages/README.md b/tests/fixtures/pages/README.md index f52d003..b496a4a 100644 --- a/tests/fixtures/pages/README.md +++ b/tests/fixtures/pages/README.md @@ -19,7 +19,7 @@ Three groups: elements each change names (`margin`, `color`, `nav`), and a lost `::before` line and a re-parented pairing (`divider`). - **Guard rails** — `blank`, `tall`, `animated`, `lazy`, `lazy-deep`, `lazy-js`, `lazy-grow`, `consent`, - `drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `unsettled-once`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`, `video-seek`, `hang`, `origin`, `cooperate`. + `drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `unsettled-once`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `scroll-spy`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`, `video-seek`, `hang`, `origin`, `cooperate`. One per defence in `src/capture.ts` / `src/config.ts`. ## Authoring rules diff --git a/tests/fixtures/pages/scroll-spy/left.html b/tests/fixtures/pages/scroll-spy/left.html new file mode 100644 index 0000000..e493e60 --- /dev/null +++ b/tests/fixtures/pages/scroll-spy/left.html @@ -0,0 +1,49 @@ + + + + +Scroll spy + + + + +
+

Scroll spy

+ +

Active: Now

+

A page whose nav follows the scroll. Scrolling to the bottom leaves Later active, so only a hook that runs after the scroll can show Soon.

+
+

The status line names the active section; it is the only text a hook changes.

+
+

Now

+

Soon

+

Later

+
+ + + diff --git a/tests/fixtures/pages/scroll-spy/right.html b/tests/fixtures/pages/scroll-spy/right.html new file mode 100644 index 0000000..0ac492f --- /dev/null +++ b/tests/fixtures/pages/scroll-spy/right.html @@ -0,0 +1,49 @@ + + + + +Scroll spy + + + + +
+

Scroll spy

+ +

Active: Now

+

A page whose nav follows the scroll. Scrolling to the bottom leaves Later active, so only a hook that runs after the scroll can show Soon.

+
+

The status line names the active section; it is the only text a hook changes.

+
+

Now

+

Soon

+

Later

+
+ + + diff --git a/tests/helpers/corpus.ts b/tests/helpers/corpus.ts index 8687355..39915d7 100644 --- a/tests/helpers/corpus.ts +++ b/tests/helpers/corpus.ts @@ -46,6 +46,7 @@ export const GUARDRAILS = [ "stripe", "frameset", "menu", + "scroll-spy", "signed-in", "fixed", "inserted", diff --git a/tests/helpers/parse.ts b/tests/helpers/parse.ts index 1c075bb..b2a98f0 100644 --- a/tests/helpers/parse.ts +++ b/tests/helpers/parse.ts @@ -277,7 +277,7 @@ export interface ReportCard { images: string[]; /** Region crop links in the findings block. */ crops: string[]; - /** The card carries the "before hook" badge. */ + /** The card carries the "hook" badge. */ hook: boolean; /** The accepted badge's reasons, or null. */ accepted: string | null; @@ -370,7 +370,7 @@ export function parseReport(html: string): Report { removed: [...card.matchAll(/
  • - ([^<]*)<\/li>/g)].map((m) => unesc(m[1]!)), images: [...card.matchAll(/ m[1]!), crops: [...card.matchAll(/ m[1]!), - hook: card.includes('before hook'), + hook: card.includes('hook'), accepted: unescOr(/accepted: ([^<]*)<\/span>/.exec(card)?.[1]), }); } diff --git a/tests/unit/cache.test.ts b/tests/unit/cache.test.ts index 6cf4c43..0745972 100644 --- a/tests/unit/cache.test.ts +++ b/tests/unit/cache.test.ts @@ -104,6 +104,8 @@ describe("keys", () => { const hooked = parseRoutes(["/a"], undefined, async () => {})[0]!; const paired = parseRoutes(["/b::/a"])[0]!; assert.notEqual(shotId(route!, 1440), shotId(hooked, 1440)); + const shotHooked = parseRoutes(["/a"], undefined, undefined, async () => {})[0]!; + assert.notEqual(shotId(route!, 1440), shotId(shotHooked, 1440)); assert.notEqual(shotId(route!, 1440), shotId(route!, 375)); assert.equal(shotId(route!, 1440), shotId(paired, 1440), "the left path doesn't matter"); }); diff --git a/tests/unit/config-load.test.ts b/tests/unit/config-load.test.ts index 92da4bd..e8f7300 100644 --- a/tests/unit/config-load.test.ts +++ b/tests/unit/config-load.test.ts @@ -110,7 +110,7 @@ describe("validation", () => { ["bad-left.mjs", /`left` must be a string/], [ "bad-routes.mjs", - /`routes\[0\]` must be a string or an object \{ left, right\?, selector\?, before\? \}/, + /`routes\[0\]` must be a string or an object \{ left, right\?, selector\?, before\?, beforeShot\? \}/, ], ["bad-widths.mjs", /`widths` must be an array of positive numbers/], ["bad-threshold.mjs", /`threshold` must be a number between 0 and 1/], @@ -167,9 +167,18 @@ describe("validation", () => { ['{ before: "click" }', /`before` must be a function/], [ '{ routes: ["/a", { left: "/a", before: async () => {} }] }', - /two routes both read as \/a; they have different before hooks — merge them into one route/, + /two routes both read as \/a; they have different hooks — merge them into one route/, ], ['{ routes: [{ left: "/a", before: {} }] }', /`routes\[0\]\.before` must be a function/], + ['{ beforeShot: "x" }', /`beforeShot` must be a function/], + [ + '{ routes: [{ left: "/a", beforeShot: {} }] }', + /`routes\[0\]\.beforeShot` must be a function/, + ], + [ + '{ routes: ["/a", { left: "/a", beforeShot: async () => {} }] }', + /different hooks — merge them/, + ], ['{ maskMedia: "yes" }', /`maskMedia` must be a boolean/], ['{ freezeVideo: "no" }', /`freezeVideo` must be a boolean/], ["{ storageState: 1 }", /`storageState` must be a non-empty path/], diff --git a/tests/visual/guardrails.test.ts b/tests/visual/guardrails.test.ts index d68d8da..5e7dc79 100644 --- a/tests/visual/guardrails.test.ts +++ b/tests/visual/guardrails.test.ts @@ -805,6 +805,46 @@ describe("before hooks", () => { assert.equal(r?.hook, true); assert.equal(site.hits("/menu") - before, 2, `the hook was retried${context(run)}`); }); + + test("a before hook can't hold a state the scroll pass changes", async () => { + const run = await hooked('{ before: async (page) => { await page.click("#soon"); } }', [ + "/scroll-spy", + ]); + assert.equal(run.code, 0, context(run)); + const r = result(results(run.outDir), "/scroll-spy", 1440); + assert.equal(r.diffPixels, 0, `the scroll pass left Soon active${context(run)}`); + assert.equal(r.hook, true); + }); + + test("a route's beforeShot runs after the scroll pass on both sides, over the top-level one, and on the recheck", async () => { + const run = await hooked( + '{ beforeShot: async () => { throw new Error("top-level ran"); }, routes: [{ left: "/scroll-spy", beforeShot: async (page) => { await page.click("#soon"); } }] }', + ); + assert.equal(run.code, 1, context(run)); + const r = result(results(run.outDir), "/scroll-spy", 1440); + assert.deepEqual(r.text.added, ["Active: Soon, built by the left side"], context(run)); + assert.deepEqual(r.text.removed, ["Active: Soon, built by the right side"], context(run)); + assert.equal(r.varies, undefined, `the recheck skipped the hook${context(run)}`); + assert.equal(r.hook, true); + assert.equal(cardFor(run, "/scroll-spy").hook, true, context(run)); + }); + + test("a beforeShot that throws is a route error naming it, and is not retried", async () => { + const before = site.hits("/menu"); + const run = await hooked( + '{ beforeShot: async () => { throw new Error("net::ERR_FAKE from the hook"); } }', + ["/menu"], + ); + assert.equal(run.code, 3, context(run)); + const [r] = results(run.outDir).results; + assert.equal( + r?.status === "error" && r.error, + "beforeShot hook failed on left: net::ERR_FAKE from the hook", + context(run), + ); + assert.equal(r?.hook, true); + assert.equal(site.hits("/menu") - before, 2, `the hook was retried${context(run)}`); + }); }); describe("storage state", () => { @@ -1299,4 +1339,24 @@ describe("shot deadline", () => { assert.equal(r?.status === "error" && r.error, "timeout after 2s at before hook on left"); assert.equal(site.hits("/menu") - before, 2, `the hook was retried${context(run)}`); }); + + test("a beforeShot that never resolves errors at the deadline, and is not retried", async () => { + const file = path.join(tempDir(), "hook.mjs"); + fs.writeFileSync(file, "export default { beforeShot: () => new Promise(() => {}) };\n"); + const before = site.hits("/menu"); + const run = await runCli( + renderdiffArgs({ + left: site.left, + right: site.right, + routes: ["/menu"], + widths: [1440], + config: file, + }), + { env: { RENDERDIFF_SHOT_TIMEOUT: "2" }, timeoutMs: 60_000 }, + ); + assert.equal(run.code, 3, context(run)); + const [r] = results(run.outDir).results; + assert.equal(r?.status === "error" && r.error, "timeout after 2s at beforeShot hook on left"); + assert.equal(site.hits("/menu") - before, 2, `the hook was retried${context(run)}`); + }); });