Sub topic 15
Golden tests for visual regressions
A golden test renders a widget to an image and compares it with a reference image stored in your repository. The earlier chapters asserted on the widget tree: text, types, properties. A golden test asserts on pixels, so it catches problems the tree cannot show, such as a wrong color, a changed padding, or a clipped shadow.
This chapter assumes you can write a testWidgets test, build a widget with pumpWidget, and run flutter test. It also assumes you know what pump does.
How a golden test works
The matcher matchesGoldenFile takes a path relative to the test file. It works in two modes:
- Compare mode is the default. The test renders the widget and compares the pixels with the reference file. Any difference above the comparator's tolerance fails the test, and Flutter writes failure images to a
failuresfolder next to the golden. - Update mode runs when you pass
--update-goldens. The test overwrites the reference file with the new render and passes.
A first golden test
The test fixes the surface size and pixel ratio, so the image has the same dimensions on every machine. It then compares the whole app view.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class PriceTag extends StatelessWidget {
const PriceTag({super.key, required this.label});
final String label;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.amber,
borderRadius: BorderRadius.circular(8),
),
child: Text(label),
);
}
}
void main() {
testWidgets('PriceTag matches the golden image', (tester) async {
tester.view.physicalSize = const Size(300, 200);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
const MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(child: PriceTag(label: r'$19.99')),
),
),
);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('goldens/price_tag.png'),
);
});
}Several details in this test matter:
tester.view.physicalSizeanddevicePixelRatioset the size of the render surface. Without them you get the default 800 by 600 surface, which makes every golden large and hard to review.addTearDownrestores the defaults, so later tests in the same file are not affected.expectLaterwithawaitis the usual form, because the image comparison is asynchronous.- The finder tells the matcher what to capture. The matcher finds the element's render object and captures the layer of its nearest repaint boundary. If you point it at a small widget inside a screen, the image may contain more than that widget. Capturing the whole
MaterialAppis the predictable choice, and aRepaintBoundaryis the way to isolate one subtree.
Creating and updating the reference image
The first run fails because no reference exists. Generate it with the following command:
flutter test --update-goldens test/price_tag_test.dartOpen the PNG and check that it looks right, then commit it with the test. After that, a plain flutter test compares against it. When you change the design on purpose, rerun with --update-goldens. Review the changed images in the pull request the same way you review code.
Fonts and the "blocky text" surprise
In tests, Flutter does not load your app's fonts or the platform's system fonts. Text renders with the Ahem test font, where every glyph is a solid square. This is deliberate: the same image comes out on every operating system, because no system font is involved.
The squares still show layout, size and color, so many teams keep them. If you want real glyphs, load a font file from your assets before pumping the widget.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> loadTestFont() async {
final loader = FontLoader('Roboto')
..addFont(rootBundle.load('assets/fonts/Roboto-Regular.ttf'));
await loader.load();
}
void main() {
setUpAll(loadTestFont);
testWidgets('title uses a real font', (tester) async {
tester.view.physicalSize = const Size(300, 100);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(fontFamily: 'Roboto'),
home: const Scaffold(body: Center(child: Text('Hello'))),
),
);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('goldens/title_roboto.png'),
);
});
}The font file must be declared under flutter: fonts: or flutter: assets: in pubspec.yaml. The family name in FontLoader must match the fontFamily in the theme. If the name differs, Flutter falls back to Ahem and the test does not tell you.
Tame the sources of flakiness
A golden test fails whenever its pixels change, so everything that changes pixels must be controlled. These are the common causes:
| Cause | What happens | Fix |
|---|---|---|
| Different default surface size | The image dimensions differ between tests or machines. | Set `physicalSize` and `devicePixelRatio` in every golden test. |
| Animations still running | The image is captured mid-transition. | Call `pumpAndSettle`, or `pump` with a fixed `Duration`, before the matcher. |
| Real fonts that differ per OS | Glyph shapes and anti-aliasing change slightly. | Use the default Ahem font, or load one bundled font in `setUpAll`. |
| Platform rendering differences | Shadows and blur differ by a few pixels between macOS, Linux and Windows. | Generate and verify goldens on one platform, usually the CI platform. |
| Debug banner | The corner banner appears in the image. | Set `debugShowCheckedModeBanner: false`. |
| Network images or clocks | Content changes between runs. | Inject fakes, as in the earlier chapter on dependencies. |
Platform differences are the most disruptive cause. If a developer on macOS regenerates the goldens and CI runs on Linux, the comparison can fail with differences of a few pixels. Pick one platform as the source of truth and document it. A common setup is to regenerate goldens only in a CI job or a container.
Testing several states
One widget usually has several looks, such as enabled, disabled, and long text. Use one golden per state and give the files names that describe the state. A small helper keeps the tests short:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> pumpGolden(WidgetTester tester, Widget child) async {
tester.view.physicalSize = const Size(300, 120);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(body: Center(child: child)),
),
);
await tester.pumpAndSettle();
}
void main() {
group('Save button', () {
testWidgets('enabled', (tester) async {
await pumpGolden(
tester,
ElevatedButton(onPressed: () {}, child: const Text('Save')),
);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('goldens/save_enabled.png'),
);
}, tags: ['golden']);
testWidgets('disabled', (tester) async {
await pumpGolden(
tester,
const ElevatedButton(onPressed: null, child: Text('Save')),
);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('goldens/save_disabled.png'),
);
}, tags: ['golden']);
});
}The tags: ['golden'] argument lets you run or skip these tests as a group. Declare the tag in dart_test.yaml at the project root, or the test runner warns about an unknown tag:
tags:
golden: {}Then run only the golden tests, or everything else:
flutter test --tags golden
flutter test --exclude-tags goldenWhen to use golden tests
Golden tests are strong for design-system components, charts, custom painters, and layouts where spacing is the requirement. They are weak for screens full of changing content. For behavior, such as "tapping Save calls the callback", tree assertions with finders are faster, clearer and less brittle.
Keep the number of goldens small and the images small. Each golden adds a binary file to review, and a change to a shared widget, such as a theme color, can change dozens of images at once.
Exercise
A golden test passes on your Mac but fails on CI (Linux) with a tiny pixel difference in a drop shadow. You did not change the widget. Name the likely cause and two ways to fix it.
Show answer
Different platforms render shadows and anti-aliasing slightly differently, so goldens generated on macOS do not match pixels rendered on Linux. Fixes: regenerate the goldens on the CI platform, for example in a CI job or Linux container, and treat that platform as the source of truth. Or keep goldens out of the default run with a tag, such as --exclude-tags golden, and run them only in the environment that created them.
Exercise
Your golden test captures find.byType(PriceTag) but the saved image shows the whole screen background as well as the tag. Why, and what do you change?
Show answer
The matcher captures the layer of the nearest repaint boundary around the found render object. PriceTag is not its own repaint boundary, so the image includes the surrounding content. Either wrap the widget in a RepaintBoundary that is the root of what you want captured, or capture the whole MaterialApp with a fixed physicalSize so the image is predictable.
Exercise
Why do the characters in your golden images show up as solid squares, and how do you get real letters?
Show answer
Widget tests use the Ahem font by default, in which every glyph is a square, so the output is the same on every operating system. To get real glyphs, load a bundled font file with FontLoader in setUpAll, declare the file in pubspec.yaml, and set the theme's fontFamily to the same family name.