Skip to main content
jg-packages

Search

    Browser tests

    jg-playwright

    Playwright helpers for end-to-end tests: horizontal overflow, loaded assets, motion, accessibility scans, secrets, and a fake microphone.

    v0.2.0Node.jsESMMIT

    npm

    npm install jg-playwright

    pnpm

    pnpm add jg-playwright

    Usage

    Check that a page fits a small phone without scrolling sideways. The check retries until the page settles, compares against the viewport’s clientWidth, so content under a classic scrollbar still fails, and names up to 8 elements past the right edge:

    ts
    import { test } from '@playwright/test';
    import { expectNoHorizontalOverflow } from 'jg-playwright';
    
    test('the pricing page fits a small phone', async ({ page }) => {
      await page.setViewportSize({ width: 320, height: 640 });
      await page.goto('/pricing');
      await expectNoHorizontalOverflow(page);
    });

    Scan a page, or part of it, for WCAG 2.0 and 2.1 level A and AA violations. A failure lists each rule with its impact and how many elements break it:

    ts
    import { expectNoAxeViolations } from 'jg-playwright/axe';
    
    await expectNoAxeViolations(page);
    await expectNoAxeViolations(page, { include: '[role="dialog"]' });

    ruleSet picks other rules: 'wcag22aa' adds WCAG 2.2 level AA, such as targets of at least 24 by 24 pixels, and 'axe-default' runs every rule axe runs by default, its best practices included, such as headings that aren’t empty:

    ts
    await expectNoAxeViolations(page, { ruleSet: 'wcag22aa' });
    await expectNoAxeViolations(page, { ruleSet: 'axe-default' });

    Wait until web fonts and every image have loaded, and layout has settled, before a screenshot. A broken image fails it, by its URL:

    ts
    import { waitForPageAssets } from 'jg-playwright';
    
    await waitForPageAssets(page);
    await expect(page).toHaveScreenshot();

    Check that reduced motion stops everything that moves or resizes. Fades and color changes are left out, because they’re safe with reduced motion:

    ts
    import { inspectMotion } from 'jg-playwright';
    
    test.use({ reducedMotion: 'reduce' });
    
    const { prefersReducedMotion, movingAnimations } = await inspectMotion(page);
    expect(movingAnimations).toStrictEqual([]); // each entry names the element and what it animates

    Fill a password or a one-time code without a failure printing it. Playwright’s error for a failed fill carries a call log that can repeat the value, so the error keeps only its first line, with the value redacted, and has no cause:

    ts
    import { fillProtectedField } from 'jg-playwright';
    
    await fillProtectedField(page.getByLabel('Password'), password, 'The password field');

    Record from a fake microphone. getUserMedia returns a steady tone, while the page’s own MediaRecorder still records and encodes it:

    ts
    import { installFakeMicrophone, waitForRecordedAudio } from 'jg-playwright';
    
    await installFakeMicrophone(page); // or { rejectFirstRequest: true } to test a refused permission
    await page.goto('/notes/new');
    await page.getByRole('button', { name: 'Record' }).click();
    await waitForRecordedAudio(page);

    Errors

    fillProtectedField throws an Exception with the code PROTECTED_FIELD_FILL_FAILED when the fill fails, and expectNoAxeViolations one with INVALID_AXE_OPTIONS for a ruleSet it doesn’t know, before it scans anything. The other failures go through Playwright’s expect, so they read like any other assertion’s.

    Browser limits

    • Headless Chromium hides scrollbars unless its --hide-scrollbars default argument is dropped with launchOptions: { ignoreDefaultArgs: ['--hide-scrollbars'] }, and WebKit and Firefox may draw overlay scrollbars, which take no width.
    • Playwright’s WebKit on Linux has no MediaRecorder, so a page there can use the fake microphone but can’t record it.
    • The fake microphone’s tone plays through an audio context, which needs an audio output device. Without one, such as Firefox on a Linux CI runner, the microphone’s track is live but silent, so waitForRecordedAudio times out.

    Generated from TSDoc

    API reference

    Every export of [email protected], 14 in all, with its signature, its errors, and an example.

    jg-playwright

    Functionsjg-playwright

    expectNoHorizontalOverflow
    function

    Asserts that the page doesn't scroll sideways, retrying until it settles. It compares the document's width with the viewport's clientWidth, which leaves out a classic scrollbar, so an overflow a scrollbar hides still fails. A failure names up to 8 elements past the right edge, by tag and classes.

    Signature
    expectNoHorizontalOverflow(page: Page): Promise<void>

    Parameters

    pagePage

    The page.

    Returns

    Promise<void>

    A promise that resolves once the page fits the viewport, or rejects with Playwright's assertion error after its expect timeout.

    Example
    import { test } from '@playwright/test';
    import { expectNoHorizontalOverflow } from 'jg-playwright';
    
    test('the pricing page fits a small phone', async ({ page }) => {
      await page.setViewportSize({ width: 320, height: 640 });
      await page.goto('/pricing');
      await expectNoHorizontalOverflow(page);
    });
    fillProtectedField
    function

    Fills a field that holds a secret, such as a password or a one-time code, without letting a failure print it. Playwright's error for a failed fill carries a call log that can repeat the value, so the error thrown instead keeps only the first line of Playwright's message, with any copy of the value replaced by [redacted], and deliberately has no cause.

    Signature
    fillProtectedField(
      field: Pick<Locator, "fill">,
      value: string,
      fieldDescription: string,
      options?: {},
    ): Promise<void>

    Parameters

    fieldPick<Locator, "fill">

    The field, such as page.getByLabel('Password').

    valuestring

    The secret.

    fieldDescriptionstring

    What the field is, for the error, such as 'The password field'.

    options?{}

    Playwright's fill options, such as { timeout: 10_000 }.

    Returns

    Promise<void>

    A promise that resolves once the field is filled.

    Throws

    • PROTECTED_FIELD_FILL_FAILED`${fieldDescription}: ${the first line of Playwright's message}`
    Example
    import { test } from '@playwright/test';
    import { fillProtectedField } from 'jg-playwright';
    
    test('signs in', async ({ page }) => {
      await page.goto('/sign-in');
      await fillProtectedField(
        page.getByLabel('Password'),
        process.env['E2E_PASSWORD'] ?? '',
        'The password field',
      );
    });
    inspectMotion
    function

    Lists the animations running in the page that move or resize an element, with whether the page sees prefers-reduced-motion: reduce, so a test can check that reduced motion stops them. An animation counts when it changes transform, translate, scale, rotate, width, or height. Fades and color changes don't, because they're safe with reduced motion.

    Signature
    inspectMotion(page: Page): Promise<IMotionInspection>

    Parameters

    pagePage

    The page.

    Returns

    Promise<IMotionInspection>

    A promise that resolves to the preference and the moving animations.

    Example
    import { expect, test } from '@playwright/test';
    import { inspectMotion } from 'jg-playwright';
    
    test.use({ reducedMotion: 'reduce' });
    
    test('the dialog opens without moving', async ({ page }) => {
      await page.goto('/settings');
      await page.getByRole('button', { name: 'Delete account' }).click();
      const { prefersReducedMotion, movingAnimations } = await inspectMotion(page);
      expect(prefersReducedMotion).toBe(true);
      expect(movingAnimations).toStrictEqual([]);
    });
    installFakeMicrophone
    function

    Gives the page a fake microphone in every document it loads from now on: getUserMedia returns a steady tone from an oscillator, while the page's own MediaRecorder still records and encodes it, so a test exercises the real recording path without a device or a permission prompt. Call it before page.goto. The tone needs an audio output device: without one, such as Firefox on a Linux CI runner, the track is live but silent.

    Signature
    installFakeMicrophone(
      page: Page,
      options?: IFakeMicrophoneOptions,
    ): Promise<void>

    Parameters

    pagePage

    The page.

    options?IFakeMicrophoneOptions

    Whether to refuse the first request, to test the page's permission error.

    Defaults to {}.

    Returns

    Promise<void>

    A promise that resolves once the fake is installed for later navigations.

    Example
    import { test } from '@playwright/test';
    import { installFakeMicrophone, waitForRecordedAudio } from 'jg-playwright';
    
    test('records a voice note', async ({ page }) => {
      await installFakeMicrophone(page);
      await page.goto('/notes/new');
      await page.getByRole('button', { name: 'Record' }).click();
      await waitForRecordedAudio(page);
      await page.getByRole('button', { name: 'Stop' }).click();
    });
    waitForPageAssets
    function

    Waits until the page looks finished, before a screenshot or a layout check: its web fonts are loaded, every <img> has loaded an image it can draw, and two animation frames have passed, so layout that depends on them has settled. A broken image fails it, naming the image. A lazy image below the fold never loads, so scroll it into view first.

    Signature
    waitForPageAssets(page: Page): Promise<void>

    Parameters

    pagePage

    The page.

    Returns

    Promise<void>

    A promise that resolves once the page's assets are ready, or rejects with Playwright's assertion error after its expect timeout.

    Example
    import { expect, test } from '@playwright/test';
    import { waitForPageAssets } from 'jg-playwright';
    
    test('the home page matches its screenshot', async ({ page }) => {
      await page.goto('/');
      await waitForPageAssets(page);
      await expect(page).toHaveScreenshot();
    });
    waitForRecordedAudio
    function

    Waits until the page's latest MediaRecorder, started after installFakeMicrophone, emits a chunk with bytes, so a test knows audio was captured before it stops the recording.

    Signature
    waitForRecordedAudio(page: Page): Promise<void>

    Parameters

    pagePage

    The page.

    Returns

    Promise<void>

    A promise that resolves once audio was recorded, or rejects with Playwright's assertion error after its expect timeout.

    Example
    import { test } from '@playwright/test';
    import { installFakeMicrophone, waitForRecordedAudio } from 'jg-playwright';
    
    test('transcribes a recording', async ({ page }) => {
      await installFakeMicrophone(page);
      await page.goto('/dictation');
      await page.getByRole('button', { name: 'Start dictation' }).click();
      await waitForRecordedAudio(page);
    });

    Constantsjg-playwright

    ERRORS
    const

    the codes for every error the package throws

    Declaration
    const ERRORS: { PROTECTED_FIELD_FILL_FAILED: "PROTECTED_FIELD_FILL_FAILED"; INVALID_AXE_OPTIONS: "INVALID_AXE_OPTIONS" }

    Typesjg-playwright

    IFakeMicrophoneOptions
    type

    options for installFakeMicrophone

    Declaration
    type IFakeMicrophoneOptions = {
        rejectFirstRequest?: boolean | undefined;
    };

    Members

    • rejectFirstRequestproperty
      boolean

      refuses the page's first microphone request with NotAllowedError, as a person who blocks the permission prompt would, then grants the next one

    IMotionInspection
    type

    what inspectMotion finds in the page

    Declaration
    type IMotionInspection = {
        prefersReducedMotion: boolean;
        movingAnimations: IMovingAnimation[];
    };

    Members

    • prefersReducedMotionproperty
      boolean

      whether the page sees prefers-reduced-motion: reduce

    • movingAnimationsproperty
      IMovingAnimation[]

      every running animation that moves or resizes an element

    IMovingAnimation
    type

    one running animation that moves or resizes an element

    Declaration
    type IMovingAnimation = {
        tagName: string;
        slot: string | null;
        properties: ISpatialProperty[];
        iterations: number | 'infinite';
        durationMs: number | null;
    };

    Members

    • tagNameproperty
      string

      the animated element's tag name, in lowercase

    • slotproperty
      string | null

      the element's data-slot attribute, which component libraries such as shadcn/ui set to name the part, or null when it has none

    • propertiesproperty
      ISpatialProperty[]

      the spatial properties it changes

    • iterationsproperty
      number | "infinite"

      how many times it plays, or 'infinite'

    • durationMsproperty
      number | null

      how long one iteration lasts, in milliseconds, or null when the duration is 'auto'

    ISpatialProperty
    type

    a property whose animation moves or resizes an element

    Declaration
    type ISpatialProperty = 'transform' | 'translate' | 'scale' | 'rotate' | 'width' | 'height';

    jg-playwright/axe

    Functionsjg-playwright/axe

    expectNoAxeViolations
    function

    Scans the page with axe-core for violations, and fails with one line per violation, naming the rule, its impact, how many elements break it, and its help text. It runs the WCAG 2.0 and 2.1 level A and AA rules unless ruleSet asks for WCAG 2.2 level AA too, 'wcag22aa', or for every rule axe runs by default, best practices included, 'axe-default'. Install @axe-core/playwright, an optional peer this function loads when it's first called, so the rest of the package works without it. Any other ruleSet, such as 'wcag22AA', throws before anything is scanned.

    Signature
    expectNoAxeViolations(page: Page, options?: IAxeOptions): Promise<void>

    Parameters

    pagePage

    The page.

    options?IAxeOptions

    What to scan, the whole page or the part a selector matches, and which rules.

    Defaults to {}.

    Returns

    Promise<void>

    A promise that resolves when the scan finds nothing, or rejects with Playwright's assertion error listing the violations.

    Throws

    • INVALID_AXE_OPTIONSThe axe rule set must be 'wcag21aa', 'wcag22aa', or 'axe-default'.
    Example
    import { test } from '@playwright/test';
    import { expectNoAxeViolations } from 'jg-playwright/axe';
    
    test('the open menu is accessible', async ({ page }) => {
      await page.goto('/');
      await page.getByRole('button', { name: 'Menu' }).click();
      await expectNoAxeViolations(page, { include: '[role="dialog"]' });
    });
    
    test('the home page meets WCAG 2.2 level AA', async ({ page }) => {
      await page.goto('/');
      await expectNoAxeViolations(page, { ruleSet: 'wcag22aa' });
    });

    Typesjg-playwright/axe

    IAxeOptions
    type

    options for expectNoAxeViolations

    Declaration
    type IAxeOptions = {
        include?: string | undefined;
        ruleSet?: IAxeRuleSet | undefined;
    };

    Members

    • includeproperty
      string

      a CSS selector for the part of the page to scan, such as an open dialog; the whole page when it's left out

    • ruleSetproperty
      IAxeRuleSet

      the rules to run; 'wcag21aa' when it's left out

    IAxeRuleSet
    type

    the rules a scan runs: 'wcag21aa', WCAG 2.0 and 2.1 levels A and AA; 'wcag22aa', those and WCAG 2.2 level AA; or 'axe-default', every rule axe runs by default, best practices included

    Declaration
    type IAxeRuleSet = 'wcag21aa' | 'wcag22aa' | 'axe-default';