Sub topic 2
Building the widget under test with pumpWidget
This chapter covers pumpWidget, the call that puts your widget into the test environment. It assumes you can write a basic testWidgets test, know the difference between StatelessWidget and StatefulWidget, and have flutter_test in dev_dependencies. You also need to be comfortable with async and await.
What pumpWidget does
A widget test has no screen and no running app. pumpWidget creates the widget tree for you. It takes one widget, makes it the root of a tree owned by the test binding, and runs a single frame (build, layout and paint). After the returned Future completes, finders can see the widgets you passed in.
await tester.pumpWidget(const MaterialApp(home: Text('Hello')));The call is asynchronous, so always await it. Forgetting await is a common source of flaky tests, because the following expect can run before the tree exists.
The test binding wraps your widget in a default view, but it adds nothing else. It supplies no Directionality, no MediaQuery, no Theme and no Navigator. Real apps get all of these from MaterialApp or WidgetsApp, so your widget usually needs that wrapper in a test as well.
Why the bare widget often fails
Pass a Text directly and the test fails:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('fails: no Directionality above Text', (tester) async {
await tester.pumpWidget(const Text('Hi'));
});
}The error reads "No Directionality widget found". Text needs to know whether to lay out left to right or right to left, and it looks for that information in an ancestor. The usual missing ancestors and their error messages are:
| Missing ancestor | Typical symptom | Fix |
|---|---|---|
| `Directionality` | "No Directionality widget found" | Wrap in `MaterialApp`, or in `Directionality` for a minimal tree |
| `MediaQuery` | "No MediaQuery widget ancestor found" | Wrap in `MaterialApp` or `WidgetsApp` |
| `Material` | "No Material widget found" (from `TextField`, `ListTile`, `InkWell`) | Put the widget inside a `Scaffold` or `Material` |
| `Navigator` | "Navigator operation requested with a context that does not include a Navigator" | Use `MaterialApp` with `home` |
| `Theme` data | Wrong colors or fonts | Pass `theme:` to `MaterialApp` |
For the smallest possible tree you can supply only Directionality:
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('minimal tree with only Directionality', (tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Text('Hi'),
),
);
expect(find.text('Hi'), findsOneWidget);
});
}This is rarely worth doing for Material widgets. In practice you wrap the widget in MaterialApp and Scaffold and move on.
The standard wrapper
Most tests use the same shape: MaterialApp, then Scaffold, then the widget under test.
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: GreetingForm()),
),
);MaterialApp supplies Directionality, MediaQuery, Theme, Navigator and localization. Scaffold supplies a Material ancestor, which text fields, list tiles and buttons need for ink effects. Screens that already contain their own Scaffold can go straight into home:. A nested Scaffold is legal but adds noise to the tree.
A reusable helper
Once you repeat this wrapper in more than a couple of tests, move it into an extension on WidgetTester:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
extension PumpApp on WidgetTester {
Future<void> pumpApp(Widget child, {ThemeData? theme}) {
return pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(body: child),
),
);
}
}
void main() {
testWidgets('pumpApp wraps the widget', (tester) async {
await tester.pumpApp(const Text('Wrapped'));
expect(find.text('Wrapped'), findsOneWidget);
expect(find.byType(Scaffold), findsOneWidget);
});
}Keep the helper thin. If it grows options for every possible ancestor, tests become harder to read, and a reader can no longer tell what environment a test runs in.
Calling pumpWidget more than once
You can call pumpWidget several times in one test. Each call hands the binding a new root widget, and Flutter reconciles it against the existing tree the same way it does when a parent rebuilds in a real app. The rule is that an element is reused when the new widget has the same runtimeType and the same key as the old one at that position. A reused element keeps its State.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class Clicks extends StatefulWidget {
const Clicks({super.key, this.label = 'Clicks'});
final String label;
@override
State<Clicks> createState() => _ClicksState();
}
class _ClicksState extends State<Clicks> {
int _n = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => _n++),
child: Text('${widget.label}: $_n'),
);
}
}
Widget app(Widget child) => MaterialApp(home: Scaffold(body: child));
void main() {
testWidgets('state survives or resets depending on the key', (tester) async {
await tester.pumpWidget(app(const Clicks()));
await tester.tap(find.byType(TextButton));
await tester.pump();
expect(find.text('Clicks: 1'), findsOneWidget);
// Same type, same (null) key: the State is reused, only the label changes.
await tester.pumpWidget(app(const Clicks(label: 'Taps')));
expect(find.text('Taps: 1'), findsOneWidget);
// A new key means a new element, so the State starts over.
await tester.pumpWidget(
app(const Clicks(key: ValueKey('fresh'), label: 'Taps')),
);
expect(find.text('Taps: 0'), findsOneWidget);
});
}This behavior is useful for testing how a widget responds to changed constructor arguments, such as didUpdateWidget. It also explains a surprising failure: if a test seems to remember state from an earlier step, the second pumpWidget may have reused the old element.
Controlling the screen size
The test environment simulates a screen of 800 by 600 logical pixels with a device pixel ratio of 1.0. That is neither a phone nor a desktop window. A layout that overflows on a small phone, or that switches to a wide layout at 1000 pixels, will not behave the way you expect unless you change the size.
Set the size through tester.view before calling pumpWidget, and register a teardown so other tests are not affected:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class LayoutLabel extends StatelessWidget {
const LayoutLabel({super.key});
@override
Widget build(BuildContext context) {
final width = MediaQuery.sizeOf(context).width;
return Text(width >= 600 ? 'wide' : 'narrow');
}
}
void main() {
testWidgets('default test screen counts as wide', (tester) async {
await tester.pumpWidget(const MaterialApp(home: LayoutLabel()));
expect(find.text('wide'), findsOneWidget);
});
testWidgets('phone-sized screen counts as narrow', (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: LayoutLabel()));
expect(find.text('narrow'), findsOneWidget);
});
}physicalSize is measured in physical pixels. Logical width equals physicalSize.width / devicePixelRatio. Setting the ratio to 1.0 keeps the arithmetic simple, so the sizes you type are the sizes your layout sees.
Text scale, locale and other inherited settings
Anything your widget reads from an ancestor can be controlled by what you pump above it. Some common cases:
- Theme: pass
theme: ThemeData.dark()toMaterialApp, or use thethemeparameter of the helper above. - Locale: pass
locale: const Locale('de')along with the delegates your app uses. Without the delegates, localized strings will not resolve. - Text scale: wrap the widget in
MediaQuerywithdata: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(2)), using aBuilderto get a context beneathMaterialApp. - Providers and other app-wide objects: wrap the widget in the same provider widgets your app uses. The next chapters cover replacing these with fakes.
Build the smallest environment that makes the widget work, and add only what a given test needs. A test that sets up ten ancestors it does not use hides the one that matters.
pumpWidget and later frames
pumpWidget runs one frame and stops. Anything that needs more than one frame, such as an animation, a Timer, or a Future that completes later, has not finished when pumpWidget returns. Taps and text entry change state, but the tree does not rebuild until you pump again. The chapter on pump and pumpAndSettle covers how to move time forward. For now, remember that pumpWidget builds the first frame and nothing more.
pumpWidget also accepts an optional duration. It advances the fake clock by that amount after building, which is the same idea as pump(duration). Most tests leave it out.
Common mistakes
- Passing a widget that needs ancestors without wrapping it, then reading the resulting error as a bug in the widget.
- Forgetting
awaitbeforepumpWidget. - Expecting a second
pumpWidgetto reset state when the type and key have not changed. - Relying on the 800 by 600 default and missing overflow or breakpoint bugs on real devices.
- Changing
tester.viewwithout resetting it.
Exercise
A test calls await tester.pumpWidget(const TextField()) and fails with "No Material widget found". Why does it fail, and what is the smallest change that fixes it while also providing Directionality and MediaQuery?
Show answer
TextField needs a Material ancestor for its ink and decoration, and the bare test tree provides none. Wrapping it fixes the problem: await tester.pumpWidget(const MaterialApp(home: Scaffold(body: TextField())));. MaterialApp supplies Directionality and MediaQuery, and Scaffold supplies Material.
Exercise
A test pumps Clicks(), taps the button once, then calls pumpWidget again with Clicks(label: 'Taps'). The expected text is Taps: 0, but the test finds Taps: 1. What causes this, and how can you make the second pumpWidget start from a fresh state?
Show answer
Both widgets have the same type and the same (null) key at the same position, so Flutter reuses the element and its State, and the counter keeps its value. Give the second widget a different key, for example Clicks(key: ValueKey('fresh'), label: 'Taps'), so the old element is discarded and a new State is created.