WebdriverIO Visual Testing: Setup and Configuration Guide
WebdriverIO is a Node.js automation framework that supports Selenium, WebDriver, and Chrome DevTools Protocol. Version 8+ includes a first-class visual testing service — @wdio/visual-service — that handles screenshot capture, baseline comparison, and diff generation without external services.
This guide covers setting up visual testing in WebdriverIO from scratch.
Prerequisites
- WebdriverIO 8+ project
- Node.js 16+
If you're starting from scratch:
npm init wdio@latest ./The setup wizard will guide you through configuration.
Installation
npm install --save-dev @wdio/visual-serviceConfiguration
Add the visual service to your wdio.conf.js:
// wdio.conf.js
import { join } from 'path'
export const config = {
// ... existing config
services: [
[
'visual',
{
// Baseline directory
baselineFolder: join(process.cwd(), 'tests', 'visual', 'baselines'),
// Directory for comparison results
screenshotPath: join(process.cwd(), 'tmp'),
// Format: {tag}-{browserName}-{width}x{height}
formatImageName: '{tag}-{browserName}-{width}x{height}',
// Save screenshots on failure
savePerInstance: false,
// Auto-create baseline on first run
autoSaveBaseline: true,
// Block out dynamic elements by default
blockOutStatusBar: true,
blockOutToolBar: true
}
]
]
}Writing Visual Tests
Full Page Comparison
describe('Homepage visual regression', () => {
it('should match the full page baseline', async () => {
await browser.url('/')
await browser.pause(500) // let animations settle
await expect(browser).toMatchFullPageSnapshot('homepage')
})
})Element Comparison
Compare a specific element rather than the full page:
describe('Navigation visual regression', () => {
it('should match the navigation baseline', async () => {
await browser.url('/')
const nav = await $('nav')
await expect(nav).toMatchElementSnapshot('navigation')
})
})Screen Comparison (Visible Viewport)
Compare only what's visible without scrolling:
it('should match the visible viewport', async () => {
await browser.url('/dashboard')
await browser.waitUntil(
async () => await $('.dashboard').isDisplayed(),
{ timeout: 5000 }
)
await expect(browser).toMatchScreenSnapshot('dashboard-viewport')
})Comparison Methods
@wdio/visual-service provides three comparison methods:
| Method | What it captures |
|---|---|
toMatchScreenSnapshot |
Current visible viewport |
toMatchFullPageSnapshot |
Entire page (scrolls automatically) |
toMatchElementSnapshot |
A specific DOM element |
Use toMatchElementSnapshot for component-level testing where full-page changes would create noise.
Thresholds and Sensitivity
Configure mismatch thresholds globally or per comparison:
// Global in wdio.conf.js
services: [
['visual', {
// ...
saveAboveTolerance: 0, // save diff if mismatch > 0%
largeImageThreshold: 2000, // optimize large image comparison
}]
]Per comparison:
await expect(browser).toMatchFullPageSnapshot('homepage', {
misMatchPercentage: 1.5, // allow 1.5% mismatch
blockOut: [
{ x: 0, y: 0, width: 1280, height: 60 } // block top bar
]
})Handling Dynamic Content
Dynamic content (timestamps, live data, ads) causes false positives. Block these areas out:
it('dashboard with dynamic data', async () => {
await browser.url('/dashboard')
const dynamicElements = await $$('[data-testid="live-counter"]')
await expect(browser).toMatchFullPageSnapshot('dashboard', {
elementBlockOuts: dynamicElements, // automatically block these elements
blockOut: [
{ x: 0, y: 0, width: 1280, height: 60 } // header with timestamps
]
})
})Multi-Browser Configuration
WebdriverIO's strength is cross-browser testing via Selenium Grid or cloud providers. Configure visual tests across browsers:
// wdio.conf.js
export const config = {
capabilities: [
{
browserName: 'chrome',
'goog:chromeOptions': { args: ['--headless=new', '--no-sandbox'] }
},
{
browserName: 'firefox',
'moz:firefoxOptions': { args: ['-headless'] }
}
],
services: [
['visual', {
baselineFolder: 'tests/visual/baselines',
// formatImageName includes {browserName} to keep baselines per browser
formatImageName: '{tag}-{browserName}-{width}x{height}',
autoSaveBaseline: true
}]
]
}Each browser gets its own baseline file because Chrome and Firefox render fonts and shadows differently.
Mobile and Responsive Testing
Use the appium service alongside visual for mobile:
// wdio.conf.js (Appium mobile config)
capabilities: [
{
platformName: 'Android',
'appium:deviceName': 'emulator-5554',
'appium:app': '/path/to/app.apk',
'appium:automationName': 'UiAutomator2'
}
]For responsive web testing, set viewport via browser capabilities:
capabilities: [
{
browserName: 'chrome',
'goog:chromeOptions': {
args: ['--headless=new', '--window-size=375,812'] // iPhone size
}
}
]Updating Baselines
When a visual change is intentional:
# Run with UPDATE_BASELINE=true to overwrite baselines
UPDATE_BASELINE=true npx wdio run wdio.conf.jsOr delete specific baseline files and re-run to regenerate them:
rm tests/visual/baselines/homepage-chrome-1280x800.png
npx wdio run wdio.conf.jsIntegration with Percy
For teams that want Percy's review workflow with WebdriverIO:
npm install --save-dev @percy/webdriverioimport percySnapshot from '@percy/webdriverio'
describe('Homepage', () => {
it('matches Percy baseline', async () => {
await browser.url('/')
await percySnapshot(browser, 'Homepage')
})
})Run with Percy CLI:
npx percy exec -- npx wdio run wdio.conf.jsCI/CD Integration
GitHub Actions
name: Visual Regression
on:
pull_request:
jobs:
visual-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Chrome
uses: browser-actions/setup-chrome@v1
- name: Install dependencies
run: npm ci
- name: Start app
run: npm start &
- name: Wait for app
run: npx wait-on http://localhost:3000
- name: Run visual tests
run: npx wdio run wdio.conf.js
- name: Upload diff artifacts on failure
if: failure()
uses: actions/upload-artifact@v3
with:
name: visual-diffs
path: tmp/
retention-days: 7Baseline Strategy in CI
The challenge: baselines committed to the repository must render identically across different machines.
Recommended approach:
- Commit baselines generated in CI (not locally)
- Use a fixed browser version in CI (pinned Chrome version)
- When updating baselines, run a CI job that regenerates them and commits the result
# Separate job to update baselines
update-baselines:
runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch'
steps:
- uses: actions/checkout@v3
- uses: browser-actions/setup-chrome@v1
- run: npm ci
- run: npm start &
- run: npx wait-on http://localhost:3000
- run: UPDATE_BASELINE=true npx wdio run wdio.conf.js
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: "chore: update visual baselines"
file_pattern: "tests/visual/baselines/**"Comparison Options Reference
await expect(browser).toMatchFullPageSnapshot('name', {
// Allowed mismatch percentage (default: 0)
misMatchPercentage: 1,
// Ignore anti-aliasing
ignoreAntialiasing: true,
// Ignore colors (structure-only comparison)
ignoreColors: false,
// Ignore transparent pixels
ignoreTransparentPixel: false,
// Area to ignore (array of {x, y, width, height})
blockOut: [],
// DOM elements to block out
elementBlockOuts: [],
// Resize baseline to match current screenshot dimensions
rawMisMatchPercentage: false
})Debugging Visual Test Failures
When a test fails:
- Check
tmp/for the diff image — it shows exactly which pixels changed - Check
tmp/for the actual screenshot — compare with the baseline manually - Common causes:
- Font rendering: Use consistent OS/browser version in CI
- Animations: Ensure
--disable-animationsin browser flags or CSSanimation: none - Network images: Use
networkidlewait strategy, notdomContentLoaded - Scroll position: Always scroll to top before full-page screenshots
// Best practice for full-page snapshots
await browser.url('/page')
await browser.waitUntil(
async () => (await browser.execute(() => document.readyState)) === 'complete',
{ timeout: 10000 }
)
await browser.execute(() => window.scrollTo(0, 0))
await browser.pause(300) // let scroll settle
await expect(browser).toMatchFullPageSnapshot('page')Summary
@wdio/visual-service makes visual regression testing a first-class citizen in WebdriverIO with minimal configuration. Key points:
- Use
toMatchElementSnapshotfor component tests,toMatchFullPageSnapshotfor page tests - Set per-browser baselines using
{browserName}informatImageName - Block dynamic content with
blockOutandelementBlockOuts - Commit CI-generated baselines (not local) for consistency
- Add the
@percy/webdriveriointegration when you need team review workflows
For teams already using WebdriverIO, the visual service is the lowest-friction path to adding visual regression coverage.