Visual regression testing with screenshots
Catch unintended visual changes before customers do: screenshot key pages on every deploy and compare them, or let monitors do it on a schedule.
8 min read
Unit tests tell you the code works. They don’t tell you the checkout button is now hidden behind the cookie banner on mobile, or that a CSS change pushed the pricing table off screen. Visual regression testing does: screenshot your key pages, compare them with how they looked before, and flag the differences.
There are two ways to do it with shotsmith: scripted comparisons in CI on every deploy, or monitors that watch production on a schedule.
Option 1: compare screenshots on every deploy
This Node script screenshots a list of pages on your preview or staging deploy, compares each with a committed baseline using pixelmatch, writes a diff image, and fails if more than half a percent of pixels changed:
// npm install pixelmatch pngjs
// Screenshots key pages, compares them with the committed baseline, and fails on visual changes.
import fs from 'node:fs/promises';
import pixelmatch from 'pixelmatch';
import { PNG } from 'pngjs';
const BASE = process.env.PREVIEW_URL ?? 'https://staging.example.com';
const PAGES = ['/', '/pricing', '/signup'];
const THRESHOLD = 0.5; // percent of pixels allowed to differ
async function capture(path) {
const params = new URLSearchParams({
access_key: process.env.SHOTSMITH_ACCESS_KEY,
url: BASE + path,
format: 'png',
full_page: 'true',
full_page_max_height: '6000', // cap endless pages so runs stay comparable
block_cookie_banners: 'true',
block_chats: 'true',
reduce_motion: 'true', // freeze animations and carousels
});
const res = await fetch(`https://shotsmith.dev/v1/take?${params}`);
if (!res.ok) throw new Error(`${path}: ${(await res.json()).error_code}`);
return PNG.sync.read(Buffer.from(await res.arrayBuffer()));
}
let failed = false;
await fs.mkdir('visual/current', { recursive: true });
for (const path of PAGES) {
const name = path === '/' ? 'home' : path.slice(1).replaceAll('/', '_');
const current = await capture(path);
await fs.writeFile(`visual/current/${name}.png`, PNG.sync.write(current));
let baseline;
try {
baseline = PNG.sync.read(await fs.readFile(`visual/baseline/${name}.png`));
} catch {
console.log(`${path}: no baseline yet, saved current capture`);
continue;
}
if (baseline.width !== current.width || baseline.height !== current.height) {
console.log(`${path}: size changed from ${baseline.width}x${baseline.height} to ${current.width}x${current.height}`);
failed = true;
continue;
}
const diff = new PNG({ width: current.width, height: current.height });
const changed = pixelmatch(baseline.data, current.data, diff.data, current.width, current.height, { threshold: 0.1 });
const percent = (changed / (current.width * current.height)) * 100;
await fs.writeFile(`visual/current/${name}.diff.png`, PNG.sync.write(diff));
console.log(`${path}: ${percent.toFixed(2)}% changed`);
if (percent > THRESHOLD) failed = true;
}
process.exit(failed ? 1 : 0);
And a GitHub Actions workflow to run it after each successful deployment, uploading the screenshots and diffs as an artifact you can download from the run:
name: visual-regression
on: [deployment_status]
jobs:
visual:
if: github.event.deployment_status.state == 'success'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 22 }
- run: npm install pixelmatch pngjs
- run: node scripts/visual-diff.mjs
env:
SHOTSMITH_ACCESS_KEY: ${{ secrets.SHOTSMITH_ACCESS_KEY }}
PREVIEW_URL: ${{ github.event.deployment_status.environment_url }}
- uses: actions/upload-artifact@v4
if: always()
with: { name: visual-diffs, path: visual/current }
When a change is intended, copy the new captures from visual/current into visual/baseline and commit them.
Make screenshots repeatable
Most false alarms come from things that change on every visit, not from your code. These options remove them:
reduce_motion=truestops animations, transitions and carousels before capturing.block_cookie_banners,block_chatsandblock_adsremove overlays that vary between visits.hide_selectorshides anything else that changes, such as timestamps, rotating testimonials, or a “users online” counter.wait_for_selectorwaits for late-loading content, so you never compare a half-loaded page.- Fix the viewport, with
viewport_widthor aviewport_device, so every run is the same size.
Option 2: monitors, with no code
For production, or for pages you don’t deploy yourself, a monitor captures a page on a schedule (every 15 minutes to weekly), compares it with the last capture, and emails you or calls a webhook when more than your threshold changes, with the changed area highlighted.
import { Shotsmith } from '@shotsmith/sdk';
const shotsmith = new Shotsmith({ accessKey: 'YOUR_ACCESS_KEY' });
const monitor = await shotsmith.monitors.create({
name: 'Production pricing page',
url: 'https://example.com/pricing',
frequency: 'hourly',
threshold: 1,
options: {
full_page: true,
hide_selectors: ['.testimonial-carousel'],
},
});
console.log(monitor.id);
<?php
require 'vendor/autoload.php';
use Shotsmith\Client;
$shotsmith = new Client('YOUR_ACCESS_KEY');
$monitor = $shotsmith->createMonitor([
'name' => 'Production pricing page',
'url' => 'https://example.com/pricing',
'frequency' => 'hourly',
'threshold' => 1,
'options' => [
'full_page' => true,
'hide_selectors' => ['.testimonial-carousel'],
],
]);
echo $monitor['id'];
curl -X POST "https://shotsmith.dev/v1/monitors" \
-H "X-Access-Key: YOUR_ACCESS_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Production pricing page",
"url": "https://example.com/pricing",
"frequency": "hourly",
"threshold": 1,
"options": {
"full_page": true,
"hide_selectors": [
".testimonial-carousel"
]
}
}'
const res = await fetch('https://shotsmith.dev/v1/monitors', {
method: 'POST',
headers: {
'X-Access-Key': 'YOUR_ACCESS_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Production pricing page',
url: 'https://example.com/pricing',
frequency: 'hourly',
threshold: 1,
options: {
full_page: true,
hide_selectors: ['.testimonial-carousel'],
},
}),
});
if (!res.ok) throw new Error((await res.json()).error_message);
console.log(await res.json());
import json
import urllib.request
body = {
"name": "Production pricing page",
"url": "https://example.com/pricing",
"frequency": "hourly",
"threshold": 1,
"options": {
"full_page": True,
"hide_selectors": [".testimonial-carousel"]
}
}
req = urllib.request.Request(
"https://shotsmith.dev/v1/monitors",
data=json.dumps(body).encode(),
headers={"X-Access-Key": "YOUR_ACCESS_KEY", "Content-Type": "application/json"},
method="POST",
)
# Raises urllib.error.HTTPError on a 4xx/5xx response
with urllib.request.urlopen(req, timeout=60) as res:
print(json.load(res))
<?php
$ch = curl_init('https://shotsmith.dev/v1/monitors');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['X-Access-Key: YOUR_ACCESS_KEY', 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'name' => 'Production pricing page',
'url' => 'https://example.com/pricing',
'frequency' => 'hourly',
'threshold' => 1,
'options' => [
'full_page' => true,
'hide_selectors' => ['.testimonial-carousel'],
],
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
]);
$response = json_decode(curl_exec($ch), true);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) >= 400) {
throw new RuntimeException($response['error_message']);
}
print_r($response);
package main
import (
"fmt"
"io"
"net/http"
"strings"
)
func main() {
body := strings.NewReader(`{
"name": "Production pricing page",
"url": "https://example.com/pricing",
"frequency": "hourly",
"threshold": 1,
"options": {
"full_page": true,
"hide_selectors": [
".testimonial-carousel"
]
}
}`)
req, _ := http.NewRequest("POST", "https://shotsmith.dev/v1/monitors", body)
req.Header.Set("X-Access-Key", "YOUR_ACCESS_KEY")
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
out, _ := io.ReadAll(res.Body)
fmt.Println(string(out))
}
require "net/http"
require "json"
body = {
"name" => "Production pricing page",
"url" => "https://example.com/pricing",
"frequency" => "hourly",
"threshold" => 1,
"options" => {
"full_page" => true,
"hide_selectors" => [".testimonial-carousel"]
}
}
res = Net::HTTP.post(
URI("https://shotsmith.dev/v1/monitors"),
body.to_json,
"X-Access-Key" => "YOUR_ACCESS_KEY",
"Content-Type" => "application/json"
)
raise res.body unless res.is_a?(Net::HTTPSuccess)
puts JSON.parse(res.body)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Request {
public static void main(String[] args) throws Exception {
var body = """
{
"name": "Production pricing page",
"url": "https://example.com/pricing",
"frequency": "hourly",
"threshold": 1,
"options": {
"full_page": true,
"hide_selectors": [
".testimonial-carousel"
]
}
}
""";
var request = HttpRequest.newBuilder(URI.create("https://shotsmith.dev/v1/monitors"))
.header("X-Access-Key", "YOUR_ACCESS_KEY")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
var res = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(res.body());
}
}
using System;
using System.Net.Http;
using System.Text;
using var http = new HttpClient();
http.DefaultRequestHeaders.Add("X-Access-Key", "YOUR_ACCESS_KEY");
var body = """
{
"name": "Production pricing page",
"url": "https://example.com/pricing",
"frequency": "hourly",
"threshold": 1,
"options": {
"full_page": true,
"hide_selectors": [
".testimonial-carousel"
]
}
}
""";
var res = await http.PostAsync(
"https://shotsmith.dev/v1/monitors",
new StringContent(body, Encoding.UTF8, "application/json")
);
res.EnsureSuccessStatusCode();
Console.WriteLine(await res.Content.ReadAsStringAsync());
Add a second opinion from AI
Pixel diffs tell you what changed, not whether it’s broken. Adding a vision_prompt such as “list any overlapping or cut-off elements” gets a plain-language verdict on the same screenshot. See automated visual QA with AI vision.