Sub topic 8
Widget tests: building a widget in a test
This chapter assumes you can write Dart with async and await, build stateless and stateful widgets, run flutter from the command line, and add dependencies in pubspec.yaml. It also assumes you have written a plain unit test with test and expect.
What a widget test is
A widget test builds a widget, or a whole small widget tree, inside a test and lets you interact with it. It runs on your development machine, with no emulator and no device. Flutter provides a test environment that runs the real framework code: build, layout, paint and gesture handling. The rendering is simulated, so a widget test runs in milliseconds, unlike an integration test on a device.
A widget test sits between a unit test and an integration test. A unit test checks logic with no UI. A widget test checks that a widget shows the right things and reacts correctly to input. An integration test checks the whole app on a real device.
Use a widget test when the behavior you care about lives in the widget tree. Examples are "the error text appears when the form is empty" and "tapping the button changes the label".
The testWidgets function
Widget tests use testWidgets instead of test. It comes from package:flutter_test, which is included in every Flutter project through the dev_dependencies section of pubspec.yaml:
dev_dependencies:
flutter_test:
sdk: flutterThe callback you pass to testWidgets receives a WidgetTester. This object is your handle on the test environment. You use it to build widgets, find them, tap them, type into them and advance time.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows a greeting', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: Text('Hello'))),
);
expect(find.text('Hello'), findsOneWidget);
});
}The callback is async because most WidgetTester methods return a Future. Always await them. A missing await is a common source of tests that pass or fail at random.
Building the widget under test
tester.pumpWidget inflates a widget and renders one frame. Whatever you pass becomes the root of the tree.
Many widgets need ancestors that a real app supplies. Text needs a Directionality. Scaffold, Icon and TextField need a Theme and MediaQuery. MaterialApp provides all of these. If you skip it, you often see errors such as "No Directionality widget found" or "No MediaQuery widget found".
The simplest fix is to wrap the widget under test in MaterialApp. For a widget that is not a full screen, also wrap it in Scaffold:
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: Center(child: MyBadge(count: 3))),
),
);Here MyBadge stands for any widget of your own.
A complete example
The widget test below uses the counter page from earlier chapters. It builds the page, checks the starting text, taps the button and checks the new text.
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('tapping the button increments the counter', (tester) async {
await tester.pumpWidget(const MaterialApp(home: CounterPage()));
expect(find.text('0'), findsOneWidget);
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('1'), findsOneWidget);
});
}The test follows the same three steps as most widget tests:
- Arrange.
pumpWidgetbuildsCounterPageinsideMaterialApp. - Act.
tester.tapsimulates a tap, andtester.pumprebuilds the tree. - Assert.
expectwithfind.textchecks what is on screen.
Save this in a file such as test/counter_page_test.dart and run it with flutter test test/counter_page_test.dart. File names must end in _test.dart for flutter test to discover them.
How the test environment works
The test environment differs from a running app in ways that matter.
Key points:
- Time is controlled by you. The framework does not run frames on its own. After
pumpWidget, nothing rebuilds until you callpumporpumpAndSettle. This is why the example callspump()after the tap:setStatemarks the widget dirty, but the new text appears only after a frame is built. - Time is fake. Timers and animations run on a fake clock. Calling
pump(Duration(seconds: 1))advances the clock by one second without waiting. - Rendering is simulated. The test binding uses a default surface of 800 by 600 logical pixels. Real image decoding and real network access do not happen.
- Real network calls fail. The test environment blocks HTTP requests and returns status 400. Replace network code with a fake instead.
- Fonts are placeholder. Text is drawn with a test font made of solid squares. Layout is correct for the font metrics, but glyphs are not realistic.
Each test gets a fresh tree
Every testWidgets call starts with an empty environment. State from one test does not leak into the next unless you store it in a global or a static field. Because of this, you build the widget again in every test, or in a helper.
A helper keeps tests short when many of them need the same wrapper:
Widget wrap(Widget child) {
return MaterialApp(home: Scaffold(body: child));
}
void main() {
testWidgets('badge shows the count', (tester) async {
await tester.pumpWidget(wrap(const Text('3')));
expect(find.text('3'), findsOneWidget);
});
}You can also use setUp inside a group, as you did for unit tests. Use it for plain Dart objects such as fakes. Do not build widgets in setUp, because the tester is not available there. Call pumpWidget inside each test.
Reading failures
When a finder does not match, the failure message names the finder and what was found. For expect(find.text('2'), findsOneWidget) on a tree that shows 1, you get a message like:
Expected: exactly one matching candidate
Actual: _TextWidgetFinder:<Found 0 widgets with text "2": []>
Which: means none were found but one was expectedTwo debugging aids help here:
debugDumpApp()prints the widget tree to the console.tester.printToConsole('message')prints text that is tied to the test output.
If the failure is a framework exception such as a layout overflow, the test reports it as a failure. Read the first error in the output, because later errors are often consequences of it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "No Directionality widget found" | The widget was built without `MaterialApp` or `Directionality` | Wrap the widget in `MaterialApp` |
| "No MediaQuery widget found" | Same as above | Wrap the widget in `MaterialApp` |
| `expect` sees the old text after a tap | No `pump` after the tap | Add `await tester.pump()` |
| The test passes or fails randomly | A `Future` was not awaited | Add `await` to every `tester` call |
| `findsOneWidget` fails with "Found 2 widgets" | The finder matches several widgets | Use a more specific finder |
| A timer is still pending at the end | The widget started a `Timer` that never finished | Advance time with `pump(duration)` or dispose the widget |
| Layout overflow error | The widget needs more than the 800 by 600 surface | Set a size with `tester.view` or fix the layout |
Setting a screen size
The default surface can be too small or too large for the layout you want to test. You can change it through the view of the test binding:
testWidgets('layout fits a small phone', (tester) async {
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const MaterialApp(home: Scaffold(body: Text('Hi'))));
expect(find.text('Hi'), findsOneWidget);
});addTearDown registers cleanup that runs after the test, even if it fails. Without the reset calls, the changed size would stay in place for later tests in the same file.
What to test, and what not to
A good widget test checks what a user can observe: text, icons, enabled and disabled buttons, and what changes after input. A weak widget test checks internals, such as the private state field _count. Such a test breaks when you refactor and says little about the behavior.
Keep widget tests small. Test one behavior per test, name the test after the behavior, and move logic that does not need the tree into unit tests. Business rules in a plain class are cheaper to test than the same rules inside a widget.
Exercise
A widget test taps a button that calls setState, then immediately runs expect(find.text('1'), findsOneWidget) and fails, although the app works correctly when you run it. What is the most likely cause, and what is the fix?
Show answer
The test never built a new frame after the tap. In a widget test, setState only marks the widget dirty, and nothing rebuilds until the test calls pump or pumpAndSettle. Add await tester.pump() after await tester.tap(...) and before the expect call.
Exercise
You write testWidgets('shows title', (tester) async { await tester.pumpWidget(const Text('Title')); }) and the test fails with a "No Directionality widget found" error. Why, and how do you fix it?
Show answer
Text needs a Directionality ancestor to know the reading direction, and pumpWidget does not add one. Wrap the widget in MaterialApp, for example MaterialApp(home: Scaffold(body: Text('Title'))), or in a Directionality widget.