Skip to content

@ogygia/testing

Other runners

Use @ogygia/testing outside the Playwright fixture. new Ogygia(driver) over Puppeteer or any page driver, the driver contract, the matchers in Vitest and Jest, and Playwright pages you manage yourself.

On this page

The Playwright fixture is a thin layer over a class you can use directly. new Ogygia(driver) gives the same four measurements and settled() over any driver that can run a function in a page, and ogygiaMatchers are plain expect.extend matchers. So a Puppeteer suite, a WebdriverIO harness or a script you run by hand can measure the same things.

import { expect, test } from 'vitest';
import puppeteer from 'puppeteer';
import { Ogygia, ogygiaMatchers } from '@ogygia/testing';

expect.extend(ogygiaMatchers);

test('home hydrates cleanly', async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setCookie({
    name: 'og_devtools',
    value: 'on',
    url: 'http://127.0.0.1:4173'
  });

  // keep the injection's promise, and wait for it before the first load
  let injected: Promise<unknown> = Promise.resolve();
  const ogygia = new Ogygia({
    evaluate: (fn, arg) => page.evaluate(fn, arg),
    addInitScript: (source) =>
      (injected = page.evaluateOnNewDocument(source))
  });
  await injected;

  await page.goto('http://127.0.0.1:4173/');
  expect(await ogygia.hydration()).toHydrateCleanly();
  await browser.close();
});

Ogygia

new Ogygia(driver, options?) takes a driver and the same options as the fixture’s ogygiaOptions (profilerKey, profilerBase, timeout, islandKey, ignoreAttributes, cpuFunctions), apart from attach and lean, which belong to the fixture. It has page(), hydration(), record(), profile(), settled(), and reports, every report taken so far, in order.

Make the Ogygia before the page’s first load. It hands the engine to the driver’s addInitScript at once but doesn’t wait for it, and has no way to yet (#2310): a load that starts before the init script is registered has no engine, and every call on it ends in testing_api_absent. So do what the fixture does: keep the addInitScript promise and await it before the first goto, as the Puppeteer and Playwright examples here do. If the injection fails, that await throws its error.

Two things the fixture does for you are yours to do here:

  • Turn measuring on. On a build, set the og_devtools=on cookie before the first load (and og_testing=lean for lean testing), as the Puppeteer example does. The dev server measures without it.
  • Keep the reports. Write ogygia.reports.map(forAttachment) wherever your CI looks, as { test, reports }, so compare can read them.

Driver

The driver is an OgygiaDriver. Only evaluate is required. The other members let a driver do what the defaults can’t:

MemberWhat it doesWithout it
evaluate(fn, arg)Runs fn(arg) in the page and returns its JSON result. Typed loosely, so any driver’s page.evaluate fits without a cast.required
addInitScript(source)Runs source in every page before the page’s own scripts (Playwright’s addInitScript, Puppeteer’s evaluateOnNewDocument). ogygia passes it the engine once, when the Ogygia is made.the page must load the engine itself
post(url, headers)Makes a POST relative to the app and returns { status, body }, for profile() and the server window of record(…, { server: true }).fetch inside the page
get(url, headers)Makes a GET relative to the app. No call uses it now: profile() POSTs.fetch inside the page
wait(ms)Waits.a timer
blockNavigation()Starts holding back the page’s document loads, for record(…, { blockNavigation: true }). Returns { stop() }, which resolves to the held loads as { url, t }.record(…, { blockNavigation: true }) throws
tagRequests(header, value)Adds a header to every request the page makes to its own origin until the returned function is called, so a serverless deployment can tie the session’s requests to its server window.requests go untagged

Without post, profile() runs fetch inside the page, so a page on the app’s origin must be open. A driver with its own post can profile with no page loaded.

Puppeteer

Puppeteer’s page.evaluate and page.evaluateOnNewDocument fit evaluate and addInitScript as they are. Add post with Node’s fetch so profile() works without an open page, and the profiler key goes in the headers it’s handed:

import type { Page } from 'puppeteer';
import type { OgygiaDriver } from '@ogygia/testing';

export function puppeteerDriver(
  page: Page,
  baseURL: string
): OgygiaDriver {
  return {
    evaluate: (fn, arg) => page.evaluate(fn, arg),
    addInitScript: (source) =>
      page.evaluateOnNewDocument(source),
    async post(url, headers) {
      const res = await fetch(new URL(url, baseURL), {
        method: 'POST',
        headers: { ...headers, origin: new URL(baseURL).origin }
      });
      return { status: res.status, body: await res.text() };
    }
  };
}

Vitest and Jest

ogygiaMatchers is an object of matcher functions in the shape Playwright, Vitest and Jest all take. Register it once with expect.extend(ogygiaMatchers), in a setup file or at the top of a test file. The matcher types are declared for Playwright only, so a Vitest or Jest suite declares them itself. In Vitest, the type parameter must read T = any, as in Vitest’s own declaration:

The matchers work on any report, including one read back from a saved ogygia.json, so a Node test can check the reports a CI run kept without a browser. They run in Node; Vitest’s browser mode runs the test file inside the page, where Ogygia can’t read its engine or load other pages.

import 'vitest';
import type { Budget } from '@ogygia/testing';

type Status =
  | 'failed'
  | 'recovered'
  | 'healed'
  | 'changed'
  | 'asleep'
  | 'clean';

declare module 'vitest' {
  interface Assertion<T = any> {
    toHaveNoFindings(opts?: {
      severity?: 'info' | 'warn' | 'error';
      ignore?: string[];
    }): T;
    toMeetBudget(budget: Budget): T;
    toHydrateCleanly(opts?: {
      allow?: Status[];
      allowAttributeChanges?: boolean;
      allowInput?: boolean;
    }): T;
  }
}

Playwright pages

When you manage Playwright pages yourself instead of using the fixture, such as two browser contexts in one test, one for a preview deploy and one for a baseline, two helpers give you what the fixture builds:

  • playwrightDriver(page, { baseURL?, onNavigationHeld? }) returns the fixture’s driver, blockNavigation and tagRequests included. Its post sends an Origin header for baseURL, since a SvelteKit app refuses a cross-site POST without one. onNavigationHeld(nav) is called each time a document load is held back, so you can note which step of your script was running.
  • turnOnDevtools(page, baseURL?, { lean? }) sets the og_devtools=on cookie (and og_testing=lean) for the page’s browser context. Without a baseURL, it sets the cookie on the first page load the page makes, on that very request.

A baseline built with an older ogygia answers with older reports. Engine versions says what’s missing from each.

import { test, expect } from '@playwright/test';
import {
  Ogygia,
  ogygiaMatchers,
  playwrightDriver,
  turnOnDevtools,
  type OgygiaDriver
} from '@ogygia/testing';

expect.extend(ogygiaMatchers);

const preview = 'https://preview.example.com';
const baseline = 'https://www.example.com';

// an Ogygia whose engine is injected before it's returned, as the fixture waits for it
async function ready(driver: OgygiaDriver): Promise<Ogygia> {
  let injected: Promise<unknown> = Promise.resolve();
  const og = new Ogygia({
    ...driver,
    addInitScript: (source) =>
      (injected = driver.addInitScript?.(source) ?? injected)
  });
  await injected;
  return og;
}

test('the preview hydrates no worse than the baseline', async ({
  browser
}) => {
  const [a, b] = await Promise.all([
    browser.newPage(),
    browser.newPage()
  ]);
  await turnOnDevtools(a, preview);
  await turnOnDevtools(b, baseline);

  const steps: string[] = [];
  const head = await ready(
    playwrightDriver(a, {
      baseURL: preview,
      onNavigationHeld: (n) => steps.push(n.url)
    })
  );
  const base = await ready(
    playwrightDriver(b, { baseURL: baseline })
  );

  await Promise.all([
    a.goto(`${preview}/pricing`),
    b.goto(`${baseline}/pricing`)
  ]);
  const [h, bl] = await Promise.all([
    head.hydration(),
    base.hydration()
  ]);

  const broken = (r: typeof h) =>
    r.islands.filter((i) => i.status === 'failed').length;
  expect(broken(h)).toBeLessThanOrEqual(broken(bl));
});