Sub topic 9
Testing async UI and timers
This chapter assumes you can write a basic widget test with testWidgets, pumpWidget, finders and pump. It also assumes you know Dart's Future, Completer and Timer. Real screens load data, show spinners, debounce input and count down. You can test all of that without waiting, because widget tests run on a fake clock.
How fake time works in testWidgets
testWidgets runs your test body inside a fake-async zone. In that zone:
Future.delayed,TimerandTimer.periodicuse a simulated clock, not the wall clock.- The clock moves only when you ask it to, through
tester.pump(Duration)ortester.pumpAndSettle(). - A one-hour delay costs nothing, because the test never waits for it.
A widget test therefore has two separate steps:
- Move time forward, by pumping.
- Look at the tree, with finders and matchers.
Forgetting step 1 is the most common async bug in widget tests. The state has changed, but the tree has not rebuilt, so your finder still sees the old UI.
Choosing a pump
Each pump variant answers a different question. The diagram shows how to pick one.
| Call | What it does | Use it for |
|---|---|---|
| `pump()` | Builds one frame, with no time passing | A `setState`, or a completed `Completer` |
| `pump(Duration)` | Advances the fake clock, then builds one frame | Timers, partial progress, intermediate states |
| `pumpAndSettle()` | Pumps in 100 ms steps until no frame is scheduled | Animations and transitions that finish |
pumpAndSettle throws a timeout error if frames never stop being scheduled. The default timeout is 10 minutes of fake time. A CircularProgressIndicator animates forever, so calling pumpAndSettle while a spinner is on screen fails. This is the main reason to prefer pump(Duration).
Controlling a Future with a Completer
The Future.delayed fake in the spine chapter works, but it ties the test to a duration. A Completer is more precise. The future finishes exactly when your test says so, which lets you assert the loading state, the success state and the error state separately.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class NameView extends StatefulWidget {
const NameView({super.key, required this.loadName});
final Future<String> Function() loadName;
@override
State<NameView> createState() => _NameViewState();
}
class _NameViewState extends State<NameView> {
late final Future<String> _name = widget.loadName();
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text('Could not load');
}
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
return Text('Hello, ${snapshot.data}');
},
);
}
}
Widget wrap(Widget child) => MaterialApp(home: Scaffold(body: child));
void main() {
testWidgets('shows the name after the future completes', (tester) async {
final completer = Completer<String>();
await tester.pumpWidget(wrap(NameView(loadName: () => completer.future)));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
completer.complete('Ada');
await tester.pump();
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('Hello, Ada'), findsOneWidget);
});
testWidgets('shows an error message when loading fails', (tester) async {
final completer = Completer<String>();
await tester.pumpWidget(wrap(NameView(loadName: () => completer.future)));
completer.completeError(Exception('offline'));
await tester.pump();
expect(find.text('Could not load'), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
});
}The order matters in each test:
pumpWidgetbuilds the first frame, and the spinner is visible.completeorcompleteErrorresolves the future.- A plain
pump()lets theFutureBuilderrebuild.
A plain pump() is enough here. No timer is involved, only a microtask, and pump flushes microtasks before it builds the frame.
Testing timers
A Timer.periodic countdown is a good example of time-driven UI. The widget below cancels its timer in dispose. This matters for the test, as explained after the code.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class Countdown extends StatefulWidget {
const Countdown({super.key, this.seconds = 3});
final int seconds;
@override
State<Countdown> createState() => _CountdownState();
}
class _CountdownState extends State<Countdown> {
late int _remaining = widget.seconds;
Timer? _timer;
@override
void initState() {
super.initState();
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() => _remaining--);
if (_remaining == 0) {
timer.cancel();
}
});
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) => Text('$_remaining');
}
void main() {
testWidgets('counts down once per second and stops at zero', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: Countdown())),
);
expect(find.text('3'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 500));
expect(find.text('3'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 500));
expect(find.text('2'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
expect(find.text('0'), findsOneWidget);
await tester.pump(const Duration(seconds: 5));
expect(find.text('0'), findsOneWidget);
});
}The test reads like a timeline:
- After 500 ms the text is still
3, because the first tick has not fired. - After 1 s in total it becomes
2. - The last two pumps show that the timer stops. Five more seconds of fake time change nothing.
The partial step is the useful part. pumpAndSettle would skip straight to the end state and could not show that 3 lasts for a full second.
Pending timers
When a test finishes, the framework checks that no timers are still pending. If your widget starts a timer and never cancels it, the test fails with a message like A Timer is still pending even after the widget tree was disposed. The test is reporting a real leak. In production, the timer would keep firing after the widget is gone, and setState would be called on a disposed State. Fix it in the widget by cancelling the timer in dispose. Do not hide the failure by pumping a large duration in the test.
Debounce and delayed actions
Debounced search boxes, snackbars that auto-dismiss and delayed navigation all follow the same recipe:
- Trigger the action.
- Pump less than the delay and assert that nothing has happened yet.
- Pump the remaining time and assert the result.
Choose a duration just under the threshold, such as 299 ms for a 300 ms debounce, to confirm the delay is not shorter than intended. Then pump past it. Testing both sides catches off-by-one mistakes in the delay value.
When you need real async: runAsync
Some work cannot run on the fake clock, such as real file I/O or an isolate. The fake-async zone never completes it, so the test hangs. tester.runAsync runs a callback in the real zone:
await tester.runAsync(() async {
// Real time passes here, so keep it short.
await Future<void>.delayed(const Duration(milliseconds: 20));
});
await tester.pump();Treat runAsync as a last resort. It makes tests slower and less deterministic. In most cases, replacing the real dependency with a fake that uses a Completer is the better fix.
Common failures
- The UI looks unchanged after a future completes. You forgot
await tester.pump()aftercomplete. pumpAndSettletimes out. Something keeps animating, usually a spinner or a looping animation. Switch topump(Duration).- The test hangs on an
await. Your ownawaiton a delayed future is waiting for fake time that never advances. Pump instead, or userunAsyncif the work is genuinely real. - A timer is still pending at the end. Cancel the timer in
dispose. - A failing future throws an unhandled error. Make sure the widget handles errors, as
snapshot.hasErrordoes above. Otherwise the error reaches the test zone and fails the test.
Exercise
A search box starts a 300 ms debounce Timer each time the user types, and runs the search when the timer fires. Describe the test steps that prove the search does not run at 299 ms but does run at 300 ms. Say which pump variant you use, and why pumpAndSettle is the wrong tool for this check.
Show answer
Build the widget with a fake search function that records its calls. Call tester.enterText(...). Then await tester.pump(const Duration(milliseconds: 299)) and assert that the fake was not called. Then await tester.pump(const Duration(milliseconds: 1)) and assert that it was called once. pump(Duration) is right because it advances the fake clock by an exact amount and builds a frame. pumpAndSettle is wrong because it keeps pumping until no frames are scheduled, so it would run the timer to completion. It could not show the state at 299 ms.