Sub topic 12
Visual regression with golden tests
This chapter covers golden tests: what they check, how to write and update them, and what makes them fail on CI. It assumes you can write a testWidgets test, use pumpWidget and pump, and run flutter test from the command line.
What a golden test checks
A widget test asserts on the widget tree: this Text exists, that button is enabled. It cannot tell you that a padding changed from 16 to 6 or that a color is wrong. A golden test closes that gap. It renders a widget to pixels and compares the result with a reference image, called the golden file, that is stored in your repository.
The first run has no reference, so you create one. Later runs compare the new render with the stored image. Any pixel difference fails the test. A visual change then has to be intentional, because you must regenerate the golden file and a reviewer sees the new image in the pull request.
Golden tests suit stable, self-contained visuals such as design-system components, themed screens, and layouts at several sizes. They are a poor fit for content that changes between runs, such as timestamps, random data, or network images.
Writing a golden test
The golden test is a normal widget test that ends with matchesGoldenFile. This file is complete and runnable. It includes a copy of CounterPage so the example stands alone.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('$_count')),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
void main() {
testWidgets('CounterPage matches the golden file', (tester) async {
await tester.pumpWidget(const MaterialApp(home: CounterPage()));
await expectLater(
find.byType(CounterPage),
matchesGoldenFile('goldens/counter_page.png'),
);
});
}Save it as test/counter_golden_test.dart. Three details matter.
- The path is relative to the test file.
goldens/counter_page.pngresolves totest/goldens/counter_page.png. Create images only through the test runner, not by hand. - You must
await expectLater. Withoutawait, the test can finish before the comparison runs and pass silently. - The finder selects what to capture. Flutter renders the nearest repaint boundary above the matched element. Use
find.byType(MaterialApp)to capture the whole app surface. Use a narrower finder, or wrap the widget in aRepaintBoundarywith a key, to capture one component.
Creating and updating goldens
A new test fails until its golden file exists. Generate the file with the update flag.
flutter test --update-goldens test/counter_golden_test.dart
flutter test test/counter_golden_test.dartThe first command writes test/goldens/counter_page.png. The second compares against it and should pass. Commit the PNG with the test.
When you change the UI on purpose, the test fails. Rerun with --update-goldens, then open the image diff in version control and check that only the intended change appears.
Reading a failure
When a comparison fails, Flutter writes images to a failures directory next to the golden file, such as test/goldens/failures. For each failure you get four images.
| File suffix | Content |
|---|---|
| `masterImage` | The stored golden file |
| `testImage` | What the test just rendered |
| `isolatedDiff` | Only the pixels that differ |
| `maskedDiff` | The golden file with the differences highlighted |
Start with maskedDiff. A thin outline around text usually means a font or rendering difference. A shifted block means a layout change. Add failures to .gitignore so these files are not committed.
Why text looks like blocks
Flutter's test environment does not use your real fonts. By default it draws text with a font called Ahem, in which every glyph is a solid square. This keeps tests independent of installed fonts, and it is why a golden of Text('Hello') shows rectangles.
Blocks are often fine, because they still show size, position, and color. If you want readable text, load a real font before the test runs. Declare the font file as an asset in pubspec.yaml, then load it.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> loadAppFont() async {
final loader = FontLoader('Roboto')
..addFont(rootBundle.load('assets/fonts/Roboto-Regular.ttf'));
await loader.load();
}
void main() {
setUpAll(loadAppFont);
// golden tests go here, using a theme with fontFamily: 'Roboto'
}The theme in the widget under test must name the same family, for example ThemeData(fontFamily: 'Roboto'). The font family name and the path above are examples, so use your own.
Controlling size and pixel density
The default test surface is 800 by 600 logical pixels at a device pixel ratio of 1. A golden of a phone screen should say so explicitly. Set the size on the test view and restore it afterward.
testWidgets('CounterPage on a phone-sized screen', (tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(const MaterialApp(home: CounterPage()));
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('goldens/counter_page_phone.png'),
);
});addTearDown runs even when the test fails, so a failure does not leak the custom size into later tests. Keep the pixel ratio at 1.0 unless you need sharp images, because larger images mean bigger repositories and slower comparisons.
To cover several sizes or themes, loop over a list of configurations and give each its own file name, such as counter_page_dark.png. One golden per state and variant is easier to review than one large image.
Settling the widget before you compare
A golden captures whatever frame is current. If an animation, a loading indicator, or a pending Future is still running, the image is a snapshot of an arbitrary moment. Settle the widget first.
- Call
await tester.pumpAndSettle()when the UI has finite animations. - Call
await tester.pump(const Duration(milliseconds: 300))to capture a specific point in an animation. - Do not call
pumpAndSettlewith an infinite animation such asCircularProgressIndicator. It times out. Pump a fixed duration instead. - Replace anything time-dependent. Inject a fixed
DateTimeor a fake clock, using the dependency injection from earlier chapters, so the render is the same on every run.
Platform differences and CI
Golden files are the most common source of "passes on my machine, fails on CI". Rendering is not guaranteed to be identical across operating systems. Font rasterization and anti-aliasing differ on macOS, Windows, and Linux, and a few differing pixels fail a strict comparison.
You have these options:
- Generate and verify goldens on one platform only, usually the one CI uses. Developers on other systems run the golden tests only through CI or a container.
- Tag golden tests and skip them locally, as shown below.
- Use a comparator that tolerates a small difference, or a package such as
alchemist, which adds platform-independent goldens and naming helpers.
To use tags, put @Tags(['golden']) above the first line of the test file, before the imports, using library; syntax or a // ignore header as your lint rules require. Declare the tag in dart_test.yaml at the project root.
tags:
golden:Then choose which tests run.
flutter test --exclude-tags golden
flutter test --tags goldenThe first command is for quick local runs. The second is the CI job that uses the reference platform.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Test fails with "Could not be compared against non-existent file" | No golden file yet | Run once with `--update-goldens` |
| Passes locally, fails on CI | Different operating system or Flutter version | Generate goldens on the CI platform and pin the SDK |
| Image is blank or tiny | Wrong finder or default 800x600 surface | Capture `MaterialApp` or set `tester.view.physicalSize` |
| Image changes on every run | Animation, clock, or random data | Settle with `pump`, inject fixed values |
| Test passes with a wrong image | `expectLater` not awaited | Add `await` |
| Test hangs and times out | `pumpAndSettle` with an endless animation | Pump a fixed duration |
When to choose a golden test
Use a golden test when appearance is the behavior you want to protect and the widget has few external dependencies. For logic, such as "tapping the button adds one", a widget test with find.text('1') is cheaper and gives clearer failures. Goldens cost more because they add binary files to the repository, they need maintenance when the design changes, and they depend on the platform. Add them for the components where an unnoticed visual change would hurt, and rely on finders and matchers elsewhere.
Exercise
Your golden test passes on your Mac but fails on the Linux CI runner with a small pixel difference around the text. Name two ways to make the suite reliable.
Show answer
Generate and verify the golden files on a single reference platform (the CI runner or a container that matches it) and pin the Flutter version, or tag the golden tests and run them only in the CI job on that platform. A tolerant comparator or a package such as alchemist is a third option.
Exercise
A golden test for a screen with a CircularProgressIndicator hangs and then fails with a timeout when it calls pumpAndSettle. Why does this happen, and what should the test do instead?
Show answer
The indicator animates forever, so the frame queue never becomes idle and pumpAndSettle never returns. Call pump with a fixed Duration, or replace the loading state with a finished state, before calling expectLater with matchesGoldenFile.