# jg-playwright

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

- **Version:** `0.2.0`
- **Runtimes:** Node.js
- **Install:** `npm install jg-playwright`
- **On npm:** [jg-playwright](https://www.npmjs.com/package/jg-playwright)
- **Source:** [packages/jg-playwright](https://github.com/jesusgraterol/jg-packages/tree/main/packages/jg-playwright)
- **Recipes:** [jg-playwright recipes](https://jg-packages.jesusgraterol.dev/packages/jg-playwright/recipes/index.md)

## 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.

## <a id="api-reference"></a>jg-playwright API reference

Every export of `jg-playwright@0.2.0`, 14 in all, with its signature, its errors, and an example. It's generated from the package's TSDoc.

### <a id="api-entry-main"></a>`jg-playwright`

- Functions: [`expectNoHorizontalOverflow`](#api-expectNoHorizontalOverflow), [`fillProtectedField`](#api-fillProtectedField), [`inspectMotion`](#api-inspectMotion), [`installFakeMicrophone`](#api-installFakeMicrophone), [`waitForPageAssets`](#api-waitForPageAssets), [`waitForRecordedAudio`](#api-waitForRecordedAudio)
- Constants: [`ERRORS`](#api-ERRORS)
- Types: [`IFakeMicrophoneOptions`](#api-IFakeMicrophoneOptions), [`IMotionInspection`](#api-IMotionInspection), [`IMovingAnimation`](#api-IMovingAnimation), [`ISpatialProperty`](#api-ISpatialProperty)

#### <a id="api-functions"></a>Functions in `jg-playwright`

##### <a id="api-expectNoHorizontalOverflow"></a>`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.

```ts
expectNoHorizontalOverflow(page: Page): Promise<void>
```

**Parameters**

- `page` `Page`: 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**

```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);
});
```

##### <a id="api-fillProtectedField"></a>`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`.

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

**Parameters**

- `field` `Pick<Locator, "fill">`: The field, such as `page.getByLabel('Password')`.
- `value` `string`: The secret.
- `fieldDescription` `string`: 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**

```ts
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',
  );
});
```

##### <a id="api-inspectMotion"></a>`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.

```ts
inspectMotion(page: Page): Promise<IMotionInspection>
```

**Parameters**

- `page` `Page`: The page.

**Returns** `Promise<IMotionInspection>`: A promise that resolves to the preference and the moving animations.

**Example**

```ts
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([]);
});
```

##### <a id="api-installFakeMicrophone"></a>`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.

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

**Parameters**

- `page` `Page`: 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**

```ts
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();
});
```

##### <a id="api-waitForPageAssets"></a>`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.

```ts
waitForPageAssets(page: Page): Promise<void>
```

**Parameters**

- `page` `Page`: 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**

```ts
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();
});
```

##### <a id="api-waitForRecordedAudio"></a>`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.

```ts
waitForRecordedAudio(page: Page): Promise<void>
```

**Parameters**

- `page` `Page`: 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**

```ts
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);
});
```

#### <a id="api-constants"></a>Constants in `jg-playwright`

##### <a id="api-ERRORS"></a>`ERRORS`

*Constant*

the codes for every error the package throws

```ts
const ERRORS: { PROTECTED_FIELD_FILL_FAILED: "PROTECTED_FIELD_FILL_FAILED"; INVALID_AXE_OPTIONS: "INVALID_AXE_OPTIONS" }
```

#### <a id="api-types"></a>Types in `jg-playwright`

##### <a id="api-IFakeMicrophoneOptions"></a>`IFakeMicrophoneOptions`

*Type*

options for installFakeMicrophone

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

**Members**

- `rejectFirstRequest: boolean` (property): refuses the page's first microphone request with NotAllowedError, as a person who blocks the permission prompt would, then grants the next one

##### <a id="api-IMotionInspection"></a>`IMotionInspection`

*Type*

what inspectMotion finds in the page

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

**Members**

- `prefersReducedMotion: boolean` (property): whether the page sees `prefers-reduced-motion: reduce`
- `movingAnimations: IMovingAnimation[]` (property): every running animation that moves or resizes an element

##### <a id="api-IMovingAnimation"></a>`IMovingAnimation`

*Type*

one running animation that moves or resizes an element

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

**Members**

- `tagName: string` (property): the animated element's tag name, in lowercase
- `slot: string | null` (property): the element's `data-slot` attribute, which component libraries such as shadcn/ui set to name the part, or null when it has none
- `properties: ISpatialProperty[]` (property): the spatial properties it changes
- `iterations: number | "infinite"` (property): how many times it plays, or 'infinite'
- `durationMs: number | null` (property): how long one iteration lasts, in milliseconds, or null when the duration is 'auto'

##### <a id="api-ISpatialProperty"></a>`ISpatialProperty`

*Type*

a property whose animation moves or resizes an element

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

### <a id="api-entry-axe"></a>`jg-playwright/axe`

- Functions: [`expectNoAxeViolations`](#api-axe-expectNoAxeViolations)
- Types: [`IAxeOptions`](#api-axe-IAxeOptions), [`IAxeRuleSet`](#api-axe-IAxeRuleSet)

#### <a id="api-axe-functions"></a>Functions in `jg-playwright/axe`

##### <a id="api-axe-expectNoAxeViolations"></a>`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.

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

**Parameters**

- `page` `Page`: 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_OPTIONS`: The axe rule set must be 'wcag21aa', 'wcag22aa', or 'axe-default'.

**Example**

```ts
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' });
});
```

#### <a id="api-axe-types"></a>Types in `jg-playwright/axe`

##### <a id="api-axe-IAxeOptions"></a>`IAxeOptions`

*Type*

options for expectNoAxeViolations

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

**Members**

- `include: string` (property): a CSS selector for the part of the page to scan, such as an open dialog; the whole page when it's left out
- `ruleSet: IAxeRuleSet` (property): the rules to run; 'wcag21aa' when it's left out

##### <a id="api-axe-IAxeRuleSet"></a>`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

```ts
type IAxeRuleSet = 'wcag21aa' | 'wcag22aa' | 'axe-default';
```
