Visual Regression Testing with Selenium
Catch layout regressions with Selenium screenshots: element captures, masking dynamic content, stable rendering, pixel diffs, Applitools, Percy, CI baselines.
Functional assertions check that the right elements exist and contain the right text. They say nothing about whether the “Pay now” button is now white text on a white background, whether the sidebar overlaps the content at 1280px, or whether a CSS refactor shifted every form label by 12 pixels. Visual regression testing fills that gap: capture a screenshot, compare it to an approved baseline, and fail when they differ beyond a threshold.
It is also the easiest kind of test to make flaky. The rest of this lesson is mostly about making screenshots deterministic, because the comparison itself is the easy part.
How Visual Regression Works
first run: capture -> no baseline -> save as baseline (needs human approval)later runs: capture -> compare with baseline -> diff within threshold? -> pass -> otherwise: fail, save diff image for reviewintended UI change: reviewer approves new capture -> it becomes the baselineThree decisions shape everything else:
| Decision | Options | Recommendation |
|---|---|---|
| What to capture | Full page, viewport, single element | Element (component) screenshots first; a few full-page shots for layout |
| How to compare | Exact pixels, pixel diff with tolerance, perceptual / AI comparison | Tolerance-based diff for open source; perceptual if you use a vendor |
| Where baselines live | In the repo, in a vendor cloud, in an artifact store | Vendor cloud or a dedicated store; in-repo only for small suites |
Capturing Screenshots
Selenium can capture the viewport (every browser), a single element (every browser), and the full scrollable page (Firefox only, natively).
// ViewportFile viewport = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Element: clipped to the element's bounding boxWebElement card = driver.findElement(By.cssSelector("[data-testid='pricing-card-pro']"));File cardShot = card.getScreenshotAs(OutputType.FILE);Files.copy(cardShot.toPath(), Path.of("target/visual/pricing-card-pro.png"), StandardCopyOption.REPLACE_EXISTING);
// Full page: Firefox onlyif (driver instanceof FirefoxDriver ff) { File full = ff.getFullPageScreenshotAs(OutputType.FILE);}# Viewportdriver.save_screenshot("visual/viewport.png")
# Elementcard = driver.find_element(By.CSS_SELECTOR, "[data-testid='pricing-card-pro']")card.screenshot("visual/pricing-card-pro.png")
# Full page: Firefox onlyif driver.name == "firefox": driver.save_full_page_screenshot("visual/full.png")const fs = require('node:fs/promises');
// Viewport (base64 PNG)const viewport = await driver.takeScreenshot();await fs.writeFile('visual/viewport.png', viewport, 'base64');
// Elementconst card = await driver.findElement(By.css("[data-testid='pricing-card-pro']"));await fs.writeFile('visual/pricing-card-pro.png', await card.takeScreenshot(), 'base64');
// Full page: no portable API in selenium-webdriver; use Firefox + BiDi// browsingContext.captureScreenshot with origin 'document', or a vendor SDK// Viewport((ITakesScreenshot)driver).GetScreenshot().SaveAsFile("visual/viewport.png");
// Elementvar card = driver.FindElement(By.CssSelector("[data-testid='pricing-card-pro']"));((ITakesScreenshot)card).GetScreenshot().SaveAsFile("visual/pricing-card-pro.png");
// Full page: Firefox onlyif (driver is FirefoxDriver ff){ ff.GetFullPageScreenshot().SaveAsFile("visual/full.png");}Element screenshots are the better default. They are smaller, faster to compare, isolate failures (“the pricing card changed” rather than “the page changed”), and are unaffected by unrelated content elsewhere on the page. Full-page screenshots are useful for a handful of layout tests per template, and in Chromium they are best taken through a vendor SDK or BiDi’s browsingContext.captureScreenshot with origin: "document", which Chrome supports. For more on screenshot plumbing, see Screenshots and Videos and the element screenshot recipe.
Making Screenshots Deterministic
A visual test is only useful if two runs against the same build produce the same pixels. These are the usual sources of noise, roughly in order of how often they bite:
| Source of noise | Fix |
|---|---|
| Window size and device pixel ratio differ between machines | Fixed window size; run in the same container image everywhere |
| Web fonts not loaded yet, or fallback fonts on CI | Wait for document.fonts.ready; install the same fonts in the CI image |
| Animations, transitions, carousels, blinking caret | Inject CSS to disable them |
| Dates, times, counters, avatars, ads | Mask the region, or stub the data |
| Lazy-loaded images still loading | Wait for img.complete on images in view, or disable lazy loading |
| Scrollbars appearing in some environments | Hide scrollbars with CSS |
| Font anti-aliasing and GPU differences between OSes | Generate and compare baselines on one OS/browser combination only |
Fix the viewport
Set an explicit window size before any visual capture, and run headless so the OS window chrome cannot vary. Remember that setSize sets the outer window; if you need an exact viewport (for breakpoints), measure window.innerWidth and adjust, or use BiDi’s browsingContext.setViewport (see Mobile Emulation and Responsive Testing).
--headless=new --window-size=1366,900 --force-device-scale-factor=1 --hide-scrollbarsThese Chrome arguments pin the size, force a device pixel ratio of 1 (so a laptop with a HiDPI display produces the same image dimensions as CI), and hide scrollbars.
Freeze animations and wait for fonts
private static final String FREEZE_CSS = """ *, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; transition: none !important; caret-color: transparent !important; scroll-behavior: auto !important; }""";
static void stabilise(WebDriver driver) { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript( "const s = document.createElement('style'); s.id = 'visual-freeze';" + "s.textContent = arguments[0]; document.head.appendChild(s);", FREEZE_CSS);
// Wait for web fonts js.executeAsyncScript("const done = arguments[arguments.length - 1];" + "document.fonts.ready.then(() => done(true));");
// Wait for in-viewport images new WebDriverWait(driver, Duration.ofSeconds(10)).until(d -> (Boolean) js.executeScript( "return [...document.images].every(i => i.complete && i.naturalWidth > 0 || i.loading === 'lazy');"));}FREEZE_CSS = """*, *::before, *::after {animation-duration: 0s !important;animation-delay: 0s !important;transition: none !important;caret-color: transparent !important;scroll-behavior: auto !important;}"""
def stabilise(driver): driver.execute_script(""" const s = document.createElement('style'); s.id = 'visual-freeze'; s.textContent = arguments[0]; document.head.appendChild(s);""", FREEZE_CSS)
driver.execute_async_script(""" const done = arguments[arguments.length - 1]; document.fonts.ready.then(() => done(true));""")
WebDriverWait(driver, 10).until(lambda d: d.execute_script( "return [...document.images].every(i => i.complete && i.naturalWidth > 0 || i.loading === 'lazy');"))const FREEZE_CSS = `*, *::before, *::after {animation-duration: 0s !important;animation-delay: 0s !important;transition: none !important;caret-color: transparent !important;scroll-behavior: auto !important;}`;
async function stabilise(driver) {await driver.executeScript(` const s = document.createElement('style'); s.id = 'visual-freeze'; s.textContent = arguments[0]; document.head.appendChild(s);`, FREEZE_CSS);
await driver.executeAsyncScript(` const done = arguments[arguments.length - 1]; document.fonts.ready.then(() => done(true));`);
await driver.wait(() => driver.executeScript( "return [...document.images].every(i => i.complete && i.naturalWidth > 0 || i.loading === 'lazy');"), 10000);}private const string FreezeCss = @"*, *::before, *::after {animation-duration: 0s !important;animation-delay: 0s !important;transition: none !important;caret-color: transparent !important;scroll-behavior: auto !important;}";
static void Stabilise(IWebDriver driver){ var js = (IJavaScriptExecutor)driver; js.ExecuteScript(@"const s = document.createElement('style'); s.id = 'visual-freeze'; s.textContent = arguments[0]; document.head.appendChild(s);", FreezeCss);
js.ExecuteAsyncScript(@"const done = arguments[arguments.length - 1]; document.fonts.ready.then(() => done(true));");
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(_ => (bool)js.ExecuteScript( "return [...document.images].every(i => i.complete && i.naturalWidth > 0 || i.loading === 'lazy');"));}Setting animation-duration: 0s rather than animation: none matters: it jumps animations to their end state, so an element that fades in ends visible. animation: none can leave it stuck at opacity: 0.
Tip: If the app uses JavaScript-driven animation (GSAP, Framer Motion, a canvas chart), CSS will not stop it. Most libraries honour
prefers-reduced-motion; emulate it with CDPEmulation.setEmulatedMedia(features[{name: "prefers-reduced-motion", value: "reduce"}]) or BiDi’s media feature emulation where available.
Mask dynamic regions
Some content is supposed to change: timestamps, “3 minutes ago”, avatars, stock prices, recommendations. Either stub the data (best: the screenshot then still verifies layout of that region) or hide it before capture.
static void mask(WebDriver driver, String... selectors) { ((JavascriptExecutor) driver).executeScript(""" for (const sel of arguments[0]) { for (const el of document.querySelectorAll(sel)) { el.style.setProperty('visibility', 'hidden', 'important'); } }""", List.of(selectors));}
mask(driver, "[data-testid='last-updated']", ".avatar", "#ad-slot");File shot = driver.findElement(By.id("dashboard")).getScreenshotAs(OutputType.FILE);def mask(driver, *selectors): driver.execute_script(""" for (const sel of arguments[0]) { for (const el of document.querySelectorAll(sel)) { el.style.setProperty('visibility', 'hidden', 'important'); } }""", list(selectors))
mask(driver, "[data-testid='last-updated']", ".avatar", "#ad-slot")driver.find_element(By.ID, "dashboard").screenshot("visual/dashboard.png")async function mask(driver, ...selectors) {await driver.executeScript(` for (const sel of arguments[0]) { for (const el of document.querySelectorAll(sel)) { el.style.setProperty('visibility', 'hidden', 'important'); } }`, selectors);}
await mask(driver, "[data-testid='last-updated']", '.avatar', '#ad-slot');const shot = await driver.findElement(By.id('dashboard')).takeScreenshot();static void Mask(IWebDriver driver, params string[] selectors){ ((IJavaScriptExecutor)driver).ExecuteScript(@" for (const sel of arguments[0]) { for (const el of document.querySelectorAll(sel)) { el.style.setProperty('visibility', 'hidden', 'important'); } }", selectors.ToList());}
Mask(driver, "[data-testid='last-updated']", ".avatar", "#ad-slot");((ITakesScreenshot)driver.FindElement(By.Id("dashboard"))).GetScreenshot().SaveAsFile("visual/dashboard.png");visibility: hidden keeps the element’s box, so the layout around it is unchanged and still verified. display: none would collapse it and shift everything after it. For network-level stubbing of the data instead, see Network Interception with BiDi and the mock API response recipe.
Comparing Images
With deterministic captures you can compare with a simple pixel diff. Two thresholds keep it robust:
- Per-pixel colour tolerance absorbs anti-aliasing noise (a channel difference of a few units out of 255).
- Overall changed-pixel ratio decides pass/fail (for example, fail when more than 0.1% of pixels differ).
Always write a diff image on failure. Nobody can review “0.4% different” without seeing where.
import javax.imageio.ImageIO;import java.awt.image.BufferedImage;
static double diffRatio(Path baseline, Path actual, Path diffOut, int tolerance) throws IOException { BufferedImage a = ImageIO.read(baseline.toFile()); BufferedImage b = ImageIO.read(actual.toFile()); if (a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight()) return 1.0;
BufferedImage diff = new BufferedImage(a.getWidth(), a.getHeight(), BufferedImage.TYPE_INT_RGB); long changed = 0; for (int y = 0; y < a.getHeight(); y++) { for (int x = 0; x < a.getWidth(); x++) { int p = a.getRGB(x, y), q = b.getRGB(x, y); int dr = Math.abs(((p >> 16) & 0xff) - ((q >> 16) & 0xff)); int dg = Math.abs(((p >> 8) & 0xff) - ((q >> 8) & 0xff)); int db = Math.abs((p & 0xff) - (q & 0xff)); boolean differs = Math.max(dr, Math.max(dg, db)) > tolerance; if (differs) changed++; diff.setRGB(x, y, differs ? 0xFF0000 : (p & 0xFEFEFE) >> 1); // red on dimmed baseline } } ImageIO.write(diff, "png", diffOut.toFile()); return (double) changed / (a.getWidth() * a.getHeight());}
double ratio = diffRatio(baselinePath, actualPath, diffPath, 8);assertTrue(ratio <= 0.001, String.format("Visual diff %.3f%%, see %s", ratio * 100, diffPath));# pip install pillowfrom PIL import Image, ImageChops
def diff_ratio(baseline, actual, diff_out, tolerance=8): a = Image.open(baseline).convert("RGB") b = Image.open(actual).convert("RGB") if a.size != b.size: return 1.0 delta = ImageChops.difference(a, b) # A pixel "differs" if any channel differs by more than the tolerance mask = delta.point(lambda v: 255 if v > tolerance else 0).convert("L") mask = mask.point(lambda v: 255 if v else 0) changed = sum(1 for v in mask.getdata() if v) overlay = Image.blend(a, Image.new("RGB", a.size, "white"), 0.6) overlay.paste((255, 0, 0), mask=mask) overlay.save(diff_out) return changed / (a.width * a.height)
ratio = diff_ratio(baseline_path, actual_path, diff_path)assert ratio <= 0.001, f"Visual diff {ratio:.3%}, see {diff_path}"// npm i pixelmatch pngjsconst fs = require('node:fs');const { PNG } = require('pngjs');const pixelmatch = require('pixelmatch').default ?? require('pixelmatch');
function diffRatio(baselinePath, actualPath, diffPath) {const a = PNG.sync.read(fs.readFileSync(baselinePath));const b = PNG.sync.read(fs.readFileSync(actualPath));if (a.width !== b.width || a.height !== b.height) return 1;
const diff = new PNG({ width: a.width, height: a.height });// threshold 0..1: perceptual colour tolerance; includeAA false ignores anti-aliasingconst changed = pixelmatch(a.data, b.data, diff.data, a.width, a.height, { threshold: 0.1 });fs.writeFileSync(diffPath, PNG.sync.write(diff));return changed / (a.width * a.height);}
const ratio = diffRatio(baselinePath, actualPath, diffPath);assert.ok(ratio <= 0.001, `Visual diff ${(ratio * 100).toFixed(3)}%, see ${diffPath}`);// dotnet add package SixLabors.ImageSharpusing SixLabors.ImageSharp;using SixLabors.ImageSharp.PixelFormats;
static double DiffRatio(string baseline, string actual, string diffOut, int tolerance = 8){ using var a = Image.Load<Rgba32>(baseline); using var b = Image.Load<Rgba32>(actual); if (a.Width != b.Width || a.Height != b.Height) return 1.0;
using var diff = new Image<Rgba32>(a.Width, a.Height); long changed = 0; for (int y = 0; y < a.Height; y++) for (int x = 0; x < a.Width; x++) { Rgba32 p = a[x, y], q = b[x, y]; int d = Math.Max(Math.Abs(p.R - q.R), Math.Max(Math.Abs(p.G - q.G), Math.Abs(p.B - q.B))); bool differs = d > tolerance; if (differs) changed++; diff[x, y] = differs ? new Rgba32(255, 0, 0) : new Rgba32((byte)(p.R / 2), (byte)(p.G / 2), (byte)(p.B / 2)); } diff.SaveAsPng(diffOut); return (double)changed / (a.Width * a.Height);}
var ratio = DiffRatio(baselinePath, actualPath, diffPath);Assert.That(ratio, Is.LessThanOrEqualTo(0.001), $"Visual diff {ratio:P3}, see {diffPath}");Wrap that in a single assertMatchesBaseline(name, element) helper that stabilises, masks, captures, creates the baseline when missing (and marks the test as needing approval rather than passing silently), compares, and attaches baseline, actual and diff to the report on failure.
The Tool Landscape
Rolling your own pixel diff is fine for a few dozen components on one browser. Past that, the hard problems are baseline storage, review workflow, cross-browser rendering and noise reduction, and that is what tools sell.
| Tool | Model | Comparison | Selenium integration | Good fit |
|---|---|---|---|---|
| Applitools Eyes | Commercial SaaS | AI perceptual (“Visual AI”), layout and content match levels | SDKs for Java, Python, JS, C# wrapping your driver; Ultrafast Grid renders DOM snapshots in many browsers | Large suites, many browsers, teams that want low-noise diffs and a review dashboard |
| Percy (BrowserStack) | Commercial SaaS | Pixel diff on DOM snapshots re-rendered in Percy’s browsers | percy-selenium SDKs for Java, Python, JS, .NET; runs via percy exec | Teams already on BrowserStack, PR-based review flow |
| Cloud grid built-ins | Commercial | Varies | Sauce Labs, LambdaTest and others offer visual comparison on their grids | Teams already on that grid |
| Open source pixel diff | Self-hosted | Pixel with tolerance (pixelmatch, Pillow, ImageSharp, ImageIO) | Your own helper as above | Small, single-browser suites; component libraries |
| Open source review servers | Self-hosted | Pixel/perceptual | Visual Regression Tracker, BackstopJS (own runner), others | Teams that want a review UI without SaaS |
A key difference: Applitools’ Ultrafast Grid and Percy upload a DOM snapshot and render it in their own browsers. Your Selenium session runs once, in one browser, and you get comparisons in many. Their noise characteristics are better than raw screenshots because rendering happens in a controlled environment. The trade-off is that content that only renders in your real browser (canvas, some web components, cross-origin iframes) may need special handling.
// io.percy:percy-java-seleniumimport io.percy.selenium.Percy;
Percy percy = new Percy(driver);driver.get("https://app.example.com/pricing");percy.snapshot("Pricing page");# pip install percy-seleniumfrom percy import percy_snapshot
driver.get("https://app.example.com/pricing")percy_snapshot(driver, "Pricing page")// npm i -D @percy/cli @percy/selenium-webdriverconst percySnapshot = require('@percy/selenium-webdriver');
await driver.get('https://app.example.com/pricing');await percySnapshot(driver, 'Pricing page');// dotnet add package PercyIO.Seleniumusing PercyIO.Selenium;
driver.Navigate().GoToUrl("https://app.example.com/pricing");Percy.Snapshot(driver, "Pricing page");Outside percy exec the snapshot calls are no-ops, so the same tests run locally without a Percy token. Applitools follows a similar pattern (eyes.open(...), eyes.check(...), eyes.close()); its SDKs change more often, so copy the setup from their current docs rather than from blog posts.
Baseline Management in CI
Baselines are where open-source visual testing usually fails organisationally. Decide these up front:
Generate baselines in CI, never on laptops. A baseline captured on a developer’s Mac will never match a capture from a Linux container. Run the visual suite in the same Docker image everywhere (see Docker and Testcontainers), and if a developer needs a new baseline, they trigger a CI job that produces it.
Key baselines by environment. Path them as baselines/<browser>-<os>-<viewport>/<test-name>.png. A Chrome upgrade that changes anti-aliasing then fails one browser’s set, which you regenerate in one go.
Branch strategy. The common approach with in-repo baselines:
- Baselines on
mainare the source of truth. - A feature branch that intentionally changes UI includes updated baselines in the same pull request, so the reviewer sees the image diff next to the CSS diff.
- A CI job (
update-baselines) regenerates and commits them on request, rather than developers copying files by hand.
Vendors (Applitools, Percy) handle branching for you: baselines follow git branches and are merged when the pull request is approved in their dashboard.
Store large baseline sets outside git. Thousands of PNGs bloat a repository quickly. Git LFS or an object store keyed by commit works for self-hosted setups.
Review is a human job. Never auto-accept new baselines on failure. A visual test that updates its own baseline will always pass and never catch anything.
Warning: Do not let visual tests be the only check for something that has a functional assertion. “The error message is shown” should be an element assertion; the visual test then catches that it is shown in the wrong colour or position. Mixing the two produces failures that are hard to diagnose.
Where Visual Tests Pay Off
- Design systems and component libraries: every component in every state, element screenshots, very low noise. The highest return of any visual testing.
- Critical templates: landing, pricing, checkout, at two or three breakpoints.
- Cross-browser layout: rendering differences that functional tests never notice.
- CSS refactors and dependency upgrades: a Tailwind or Bootstrap major upgrade with a visual suite in place is a calm afternoon instead of a week of bug reports.
Keep the visual suite separate from the functional suite (a tag or separate job), run it on every pull request that touches front-end code, and keep it small enough that people review the diffs instead of rubber-stamping them.
Summary
- Prefer element screenshots; use Firefox or a vendor for full-page captures.
- Determinism is the whole game: fixed viewport and scale factor, frozen animations, loaded fonts and images, masked or stubbed dynamic content, one OS/browser per baseline set.
- A tolerance-based pixel diff with a diff image is enough for small suites; Applitools and Percy pay for themselves on large, multi-browser ones.
- Generate baselines in CI, review changes like code, and never auto-accept.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.