# Deterministic screenshots

> Make browser screenshots the same on every run, so VisualCI shows only real changes, with recipes for Playwright, Cypress and Storybook.

Source: https://visualci.com/docs/screenshots/deterministic/
All of VisualCI's documentation: https://visualci.com/llms.txt

A screenshot test is only useful when the same code gives the same pixels. Anything that changes between runs of
the same commit (the time, a random avatar, an animation caught halfway, a font that loaded late) shows up in VisualCI
as a change somebody has to look at. Fix these in the tests, once, rather than approving the same noise every week.

## Checklist

| Source of noise | Fix |
| --- | --- |
| `Math.random`, generated test data | Seed it: the same seed gives the same data |
| Web fonts | Self-host them, and wait for `document.fonts.ready` |
| System fonts and emoji | Run in a pinned CI image with the fonts installed |
| CSS animations and transitions | Reduced motion, and turn them off for the screenshot |
| GIFs, videos, canvases | Replace them with a still, or pause them on a fixed frame |
| `Date.now()`, "3 minutes ago" | Pin the clock |
| Dates and numbers | Pin the timezone and locale |
| API calls, third-party scripts | Answer from fixtures, and block everything else |
| Lazy-loaded images | Wait for every image to finish loading |
| Viewport, scrollbars, pixel ratio | Fix the viewport size, hide scrollbars, use a device pixel ratio of 1 |
| Text cursor, hover, focus | Hide the caret, and move the mouse away |

What's left after this (anti-aliasing that differs slightly between runs) is what a
[threshold](https://visualci.com/docs/screenshots.md#thresholds) is for. A threshold can't fix a clock or an animation: those change far
more pixels than anti-aliasing does.

## Find what's flaky

Run the suite twice on the same commit and compare the files. Each file that differs has something on this list:

```sh
npx playwright test && mv screenshots run1
npx playwright test && mv screenshots run2
diff <(cd run1 && find . -name '*.png' | sort | xargs sha256sum) \
     <(cd run2 && find . -name '*.png' | sort | xargs sha256sum)
```

Run it in CI's image, since that's where the baselines come from.

VisualCI points at likely suspects too: a change whose content flipped back and forth over its branch's recent builds
(A, B, A, B) is marked **flaky?** on the build page and `flaky: true` in `get_build`. It's only a hint: nothing is
ignored or approved because of it.

## Fonts

Text is most of a screenshot, and fonts are the most common difference between machines.

- **Self-host web fonts.** Serve the font files with the app instead of loading them from Google Fonts or another CDN,
  so a slow or blocked request can't fall back to another font.
- **Wait for them.** `document.fonts.ready` resolves when the fonts the page uses have loaded. Take the screenshot
  after it.
- **Pin the machine.** System fonts, emoji and font rendering differ between operating systems and between versions of
  the same one. Take screenshots in a pinned Docker image (for example `mcr.microsoft.com/playwright:v1.65.0-noble`,
  matching your Playwright version) rather than whatever the CI runner has today. Install any font the app relies on
  (`fonts-noto-color-emoji` for emoji) in that image.

## Motion

Turn on reduced motion (`prefers-reduced-motion: reduce`), so a well-behaved app skips its own animations, then
turn off what's left with CSS:

```css
*, *::before, *::after {
  animation-duration: 0s !important;
  animation-delay: 0s !important;
  transition-duration: 0s !important;
  transition-delay: 0s !important;
  caret-color: transparent !important;
}
```

Zero durations end each animation at once, rather than leaving it wherever it was when the screenshot was taken.

CSS doesn't stop a GIF, a video or a canvas:

- **GIFs:** serve a still image in their place in tests (a route that answers `*.gif` with a PNG of the first frame),
  or hide them.
- **Videos:** pause each one on a fixed frame, and wait for that frame to load:
  `video.pause(); video.currentTime = 0`. A `poster` image with `preload="none"` is simpler still.
- **Canvases and WebGL:** pin the data they draw, the clock they animate by, and the random numbers they use, or hide
  them.

## Time

Pin the clock to a fixed instant, so "today", "3 minutes ago", copyright years and countdowns render the same on
every run. Pin the timezone and locale too: the same instant is a different date in Auckland and in London, and
`1,000.50` is `1.000,50` in Germany.

Pin a time of day that's far from midnight in every timezone your tests use, so a date never depends on which side of
midnight the run lands.

## Randomness and data

Seed everything random: generated test data (`faker.seed(1)`), shuffled lists, random avatars and colours, and
`Math.random` itself (replace it with a seeded generator before the app loads; the recipes below do this). Create
test records in the same order with the same values, so IDs and sort orders don't move between runs.

## Network

A screenshot should depend only on the code under test:

- answer the app's API calls from fixtures, or from a test server seeded the same way every run;
- block third-party requests (analytics, chat widgets, ads, maps, embeds), which load late or not at all, and change
  without warning;
- wait for the network to go quiet, and for lazy images to load, before the screenshot.

## Viewport and pixels

Fix the viewport's width and height, and the device pixel ratio (1, unless you're testing high-density screens on
purpose: a screenshot from a Retina laptop is twice the size of one from CI). Hide scrollbars, which differ between
operating systems and appear only when content overflows. Hide the text cursor, and move the mouse away from
anything with a hover state.

## Playwright

Most of this is configuration. In `playwright.config.ts`:

```ts
import { defineConfig } from '@playwright/test'

export default defineConfig({
  use: {
    viewport: { width: 1280, height: 800 },
    deviceScaleFactor: 1,
    timezoneId: 'UTC',
    locale: 'en-US',
    colorScheme: 'light',
    reducedMotion: 'reduce',
  },
})
```

Then a fixture that pins the clock and `Math.random`, blocks third parties and waits before each screenshot:

```ts
// tests/fixtures.ts
import { test as base, type Page } from '@playwright/test'

export const test = base.extend({
  page: async ({ page }, use) => {
    await page.clock.install({ time: new Date('2026-01-15T12:00:00Z') })
    await page.addInitScript(() => {
      let seed = 1
      Math.random = () => {
        seed = (seed + 0x6d2b79f5) | 0
        let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
        t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
        return ((t ^ (t >>> 14)) >>> 0) / 4294967296
      }
    })
    // Abort everything but the app under test (change localhost to its host).
    await page.route(/^https?:\/\/(?!localhost[:/])/, (route) => route.abort())
    await use(page)
  },
})

export async function screenshot(page: Page, name: string) {
  await page.evaluate(() => document.fonts.ready)
  await page.waitForLoadState('networkidle')
  await page.addStyleTag({ content: '::-webkit-scrollbar { display: none } html { scrollbar-width: none }' })
  await page.mouse.move(0, 0)
  await page.screenshot({ path: `screenshots/${name}.png`, fullPage: true, animations: 'disabled', caret: 'hide' })
}
```

`animations: 'disabled'` finishes CSS animations and transitions (and cancels infinite ones) just for the
screenshot. To hide one element that can't be made stable, pass `mask: [page.locator('.live-chart')]`.

`page.clock.install` starts the page's clock at that instant and lets it run, so the app's timers still fire and a
page that shows seconds still shows the same ones. To stop time altogether (a clock that ticks every millisecond),
call `page.clock.pauseAt(...)` after it, and move time on with `page.clock.runFor(1000)` when the app needs a timer to
fire.

## Cypress

In `cypress.config.js`, fix the viewport and turn on reduced motion and a pixel ratio of 1 in Chrome:

```js
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  screenshotOnRunFailure: false,
  e2e: {
    viewportWidth: 1280,
    viewportHeight: 800,
    setupNodeEvents(on) {
      on('before:browser:launch', (browser, launchOptions) => {
        if (browser.family === 'chromium') {
          launchOptions.args.push('--force-prefers-reduced-motion', '--force-device-scale-factor=1', '--hide-scrollbars')
        }
        return launchOptions
      })
    },
  },
})
```

Run it with the timezone pinned, since Cypress's browser uses the machine's: `TZ=UTC npx cypress run --browser chrome`.

In `cypress/support/e2e.js`, pin the clock, seed `Math.random` and block third parties before every test (change
`localhost` to the app's host):

```js
beforeEach(() => {
  cy.clock(Date.UTC(2026, 0, 15, 12), ['Date'])
  cy.intercept({ url: /^https?:\/\/(?!localhost[:/])/ }, { statusCode: 204, body: '' })
  cy.on('window:before:load', (win) => {
    let seed = 1
    win.Math.random = () => {
      seed = (seed * 16807) % 2147483647
      return (seed - 1) / 2147483646
    }
  })
})

Cypress.Commands.add('stableScreenshot', (name) => {
  cy.document().its('fonts.status').should('equal', 'loaded')
  cy.document().then((doc) => {
    const style = doc.createElement('style')
    style.textContent = '*, *::before, *::after { animation-duration: 0s !important; transition-duration: 0s !important; caret-color: transparent !important }'
    doc.head.appendChild(style)
  })
  cy.screenshot(name, { capture: 'fullPage' })
})
```

`cy.clock(now, ['Date'])` pins only `Date`, so the app's own timers still run. `cy.screenshot` already pauses timers
and animations while it captures (`disableTimersAndAnimations`, on by default). Answer API calls with
`cy.intercept('GET', '/api/**', { fixture: '…' })`.

## Storybook

Screenshot every story with the [Storybook test runner](https://storybook.js.org/docs/writing-tests/test-runner),
which visits each story in Playwright. In `.storybook/test-runner.ts`:

```ts
import { waitForPageReady, type TestRunnerConfig } from '@storybook/test-runner'

const config: TestRunnerConfig = {
  async preVisit(page) {
    await page.setViewportSize({ width: 1280, height: 800 })
    await page.emulateMedia({ reducedMotion: 'reduce', colorScheme: 'light' })
  },
  async postVisit(page, context) {
    await waitForPageReady(page)
    await page.evaluate(() => document.fonts.ready)
    await page.screenshot({ path: `screenshots/${context.id}.png`, animations: 'disabled', caret: 'hide' })
  },
}

export default config
```

Pin the clock and the data in `.storybook/preview.ts`, only when a test runner drives the browser, so stories still
show live data when you browse them:

```ts
import MockDate from 'mockdate'
import { faker } from '@faker-js/faker'

if (navigator.webdriver) {
  MockDate.set('2026-01-15T12:00:00Z')
  faker.seed(1)
}
```

Run it against a static build, in the pinned image, with the timezone set, then upload:

```sh
npx storybook build --quiet
npx concurrently -k -s first \
  "npx http-server storybook-static --port 6006 --silent" \
  "npx wait-on tcp:6006 && TZ=UTC npx test-storybook --url http://127.0.0.1:6006"
visualci upload --platform chromium-linux --threshold 0.1 screenshots
```

A story's id (`button--primary`) becomes its snapshot's name.

## Then

- Give each browser and operating system its own baseline with `--platform`: see [Platforms](https://visualci.com/docs/screenshots.md#platforms).
- Set a small [threshold](https://visualci.com/docs/screenshots.md#thresholds) for anti-aliasing.
- Send the screenshots: [Playwright](https://visualci.com/docs/screenshots/playwright.md), [Cypress](https://visualci.com/docs/screenshots/cypress.md), or any
  folder of PNGs with `visualci upload`.
