Skip to main content
JUMP TO:Quick StartCLI CommandsConfigurationPlaywright APIMCP ServerGitHub Actions
Reference / API Reference(9 of 37)

API Reference

Complete TypeScript API reference for visualTest(page, name, options), VisualTestOptions, and VisualTestResult in @frontguard/playwright.

Perceptual Diff Engine and Spatial DOM-Cluster Attribution
FIG 01 · SPATIAL CLUSTERS & DOM ATTRIBUTION — PIXELMATCH, SSIM, BOUNDING BOXES & TARGET SELECTOR

Signature

typescript
visualTest(
  page: Page,
  name: string,
  options?: VisualTestOptions,
): Promise<VisualTestResult>

Options

Options include threshold, selector (component-scoped locator capture), fullPage, mask, maskRegions, redactSensitive, waitForStable, freezeTime (boolean, epoch ms number, or ISO 8601 date string), seedRandom (boolean or numeric PRNG seed), blockUrls (URL patterns to block during capture), captureAriaSnapshot (stores the ARIA tree beside the PNG and diffs it as text; a mismatch does not change passed), textSnapshot (json and markdown selectors stored the same way), optional AI (openai, anthropic, gemini, or custom baseUrl), baselineDir, and update. Threshold is the fraction of pixels that may differ (0-1).

OptionTypeDefaultDescription
thresholdnumber (0-1)0.01Fraction of pixels allowed to differ before passed becomes false (0.01 = 1%).
selectorstringundefinedCSS selector to capture a specific component instead of the full viewport.
fullPagebooleantrueCapture the full scrollable page height (ignored when selector is set).
waitForStableboolean | { maxAttempts?: number, intervalMs?: number }falseWait for fonts, then compare consecutive captures using threshold. Defaults: maxAttempts 3, intervalMs 80.
redactSensitiveboolean | string[]falseMask password, credit-card (autocomplete^="cc-"), one-time-code, and [data-frontguard-redact] / [data-sensitive] elements (plus any custom selectors) before capture.
freezeTimeboolean | number | stringundefinedFreeze page.clock and Date.now() via epoch ms or ISO 8601 string (e.g., "2026-01-01T00:00:00Z").
seedRandomboolean | numberundefinedOverride Math.random() with a deterministic Mulberry32 PRNG (true uses seed 42).
blockUrlsstring[]undefinedAbort matching network requests via page.route() during capture and clean up afterward.
captureAriaSnapshotbooleanfalseStore the ARIA tree beside the PNG and diff it as text. A mismatch does not change passed. axe-core remains the accessibility plugin.
textSnapshot{ json?: string, markdown?: string }undefinedSelectors whose text is stored as .json or .md beside the PNG. A mismatch does not change passed.
maskstring[]undefinedCSS selectors to cover with solid neutral boxes before screenshot capture.
maskRegionsArray<{ x, y, width, height }>undefinedExplicit pixel bounding boxes to mask out of comparison.
aiboolean | { provider: 'openai'|'anthropic'|'gemini', model?, baseUrl?, maxOutputTokens?, timeoutMs? }falseRun optional BYOK vision analysis when a diff exceeds threshold. A failure is returned as aiError and logged once per run.
baselineDirstring'__visual_baselines__'Directory where baseline, actual, and diff PNGs are stored.
updatebooleanprocess.env.FRONTGUARD_UPDATE === "1"Overwrite the existing baseline PNG with the current capture.

Result

The result includes passed, diffPercentage, baselinePath, currentPath, optional diffPath, boolean settled when waitForStable is enabled, clusters with bbox/rawDiffPixels/targetSelector, optional ariaSnapshot and AI output, SSIM, and isNewBaseline. Compare the returned result in your test; the function does not call a Playwright assertion for you.

FieldTypeDescription
passedbooleanTrue if diffPercentage <= threshold (or if a new baseline was created).
diffPercentagenumber (0-1)Ratio of changed pixels to total pixels (0.015 = 1.5%).
ssimnumber (0-1)Structural similarity score between baseline and current image (1.0 = identical).
isNewBaselinebooleanTrue when no prior baseline existed and a new baseline PNG was written.
baselinePathstringFile path to the baseline PNG.
currentPathstringFile path to the current PNG.
diffPathstring | undefinedFile path to the diff PNG when one was written.
clustersPlaywrightDiffCluster[]8-connected spatial diff regions: { id, bbox: { x, y, width, height }, rawDiffPixels, targetSelector? }.
settledboolean | undefinedWhether captures converged within maxAttempts; present when waitForStable is enabled.
blockedRequestsCountnumberNumber of network requests aborted by blockUrls.
ariaSnapshotstringPlaywright ARIA tree YAML/text snapshot when captureAriaSnapshot: true.
textSnapshotsArray<{ kind, status, path, excerpt? }>Text diff beside the PNG. status is match, mismatch, new, or error. A mismatch excerpt does not change passed.
ai{ classification: string, severity: string, explanation: string } | undefinedOptional vision model triage result when ai is enabled and a diff occurred.

Inspecting spatial clusters in tests

tests/checkout-regression.spec.ts
import { test, expect } from '@playwright/test'
import { visualTest } from '@frontguard/playwright'

test('checkout summary layout stays locked', async ({ page }) => {
  await page.goto('/checkout')
  const result = await visualTest(page, 'checkout-summary', {
    waitForStable: true,
    captureAriaSnapshot: true,
  })

  if (!result.passed && result.clusters?.length) {
    console.error('Regressed DOM selectors:', result.clusters.map((c) => c.targetSelector))
  }
  expect(result.passed).toBe(true)
})