Ensuring Consistent Rendering State
To guarantee a consistent rendering state across both headed and headless contexts, you must explicitly define the browser context parameters to override environment-specific defaults. Relying on the system's native resolution or the browser's default headless viewport often leads to the layout shifts and visibility failures seen in CI/CD pipelines.
The Technical Divergence
The discrepancy usually stems from two factors: the default viewport and GPU acceleration. In headed mode, the browser often inherits the OS window size or a default profile. In headless mode, Playwright defaults to a 1280x720 viewport. If your application uses responsive design (CSS media queries), an element that is visible at 1920x1080 (local) may be hidden or shifted at 1280x720 (CI), causing auto-waiting logic to time out because the element is not "stable" or "visible" according to Playwright's actionability checks.
Implementation Steps for Parity
- Explicitly Define Viewport: Set a fixed viewport in
playwright.config.ts to ensure the browser renders the same layout regardless of the environment. - Standardize Device Scale Factor: Set the
deviceScaleFactor to 1 to prevent high-DPI (Retina) screens from altering element coordinates. - Force Consistent User Agents: Some sites render differently based on the User Agent string, which can vary between headless and headed modes.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Force a consistent viewport across all environments
viewport: { width: 1280, height: 720 },
// Ensure consistent pixel density
deviceScaleFactor: 1,
},
});
Verification Process
To verify that the rendering is identical, run your tests locally in both modes using the same config:
- Local Headless:
npx playwright test - Local Headed:
npx playwright test --headed
If the tests pass in both, the disparity is likely resolved. If they still differ, check whether your CI environment is missing specific fonts that are present locally, as font substitution can cause layout shifts that viewport settings alone cannot fix.
Diagnostic Requirement
Are you using a custom Docker image for your CI/CD runner, or the official Playwright image? Missing system fonts in custom images are a common cause of residual layout differences, and the fix differs (installing font packages) from viewport configuration.