Implementation:Microsoft Playwright Comparators
Overview
Comparators provides the visual and content comparison engine for Playwright's assertion system, supporting PNG, JPEG, text, and binary comparisons with configurable thresholds.
Description
This module provides the getComparator factory function that returns the appropriate comparison function based on MIME type. Supported comparators:
- image/png and image/jpeg -- pixel-level comparison using either pixelmatch or SSIM algorithms with configurable threshold, maxDiffPixels, and maxDiffPixelRatio
- text/plain -- text comparison with unified diff output
- binary -- byte-level buffer comparison
Image comparison handles size mismatches by padding smaller images, decodes JPEG using jpegjs, and generates diff images highlighting differences.
Usage
Used by Playwright's expect assertions for screenshot and snapshot comparisons.
Code Reference
Source Location
packages/playwright-core/src/server/utils/comparators.ts (134 lines)
Function Signatures
export type ImageComparatorOptions = {
threshold?: number;
maxDiffPixels?: number;
maxDiffPixelRatio?: number;
comparator?: string;
};
export type ComparatorResult = { diff?: Buffer; errorMessage: string } | null;
export type Comparator = (actualBuffer: Buffer | string, expectedBuffer: Buffer, options?: any) => ComparatorResult;
export function getComparator(mimeType: string): Comparator;
export function compareBuffersOrStrings(actualBuffer: Buffer | string, expectedBuffer: Buffer): ComparatorResult;
Import
import { getComparator } from './server/utils/comparators';
import type { ComparatorResult, ImageComparatorOptions } from './server/utils/comparators';
I/O Contract
Inputs
mimeType: string-- determines which comparator to useactualBuffer: Buffer | string-- the actual contentexpectedBuffer: Buffer-- the expected contentoptions-- threshold, max diff pixels, comparator type
Outputs
- Returns
nullif comparison passes - Returns
{ errorMessage, diff? }if comparison fails, with optional diff image
Related Pages
- Microsoft_Playwright_Pixelmatch -- Pixel-level comparison algorithm
- Microsoft_Playwright_ImageCompare -- SSIM comparison algorithm
- Microsoft_Playwright_ImageUtils -- Image padding and scaling
- Microsoft_Playwright_ExpectUtils -- Expect assertion utilities