Sub topic 13
Debugging failing widget tests
This chapter assumes you can write a basic testWidgets test, use finders and matchers, and know the difference between pump and pumpAndSettle. It covers how to find out why a widget test fails and how to fix the failure.
Start with the failure message
Flutter's test output is usually specific, so read it before you change any code. Most failures fall into a few groups.
| Message or symptom | Usual cause |
|---|---|
| `Expected: exactly one matching candidate`, `Actual: _TextFinder:<zero widgets with text "X">` | The widget is not in the tree. Maybe you forgot to `pump`, the text differs, or the widget is not built yet. |
| `Actual: ... <2 widgets with text "X">` | The finder is too broad. |
| `Bad state: Too many elements` | You called `tester.widget`, `tester.tap` or `tester.state` on a finder that matches several widgets. |
| `Bad state: No element` | The same calls, but the finder matches nothing. |
| `pumpAndSettle timed out` | Something keeps scheduling frames, such as an infinite animation. |
| `No Material widget found` or `No Directionality widget found` | The widget under test was built without the ancestors it needs. |
| `A RenderFlex overflowed` | The layout does not fit the test window. |
| `A Timer is still pending even after the widget tree was disposed` | Your code created a timer that was never cancelled or advanced. |
| `Warning: A call to tap() ... would not hit test` | The tap landed on something other than the target widget. |
Triage flow
Work from the cheapest check to the most expensive.
Dump the widget tree
When a finder matches nothing, look at what is in the tree. debugDumpApp() prints the whole widget tree to the console. tester.printToConsole prints your own messages in a way that stays readable in test output. Finder.evaluate() returns the matching elements, so you can count them.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('inspect the tree when a finder fails', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: Text('Hello'))),
);
debugDumpApp();
final finder = find.text('Hello');
tester.printToConsole('matches: ${finder.evaluate().length}');
expect(finder, findsOneWidget);
});
}The dump lists each widget with its type, key and properties. Check for three things:
- The widget you expect is present.
- Its text matches your finder exactly, including case and whitespace.
- It sits where you think it does, for example under the right
Scaffold.
debugDumpRenderTree() prints the render objects with their sizes and constraints. Use it for layout problems. debugDumpSemanticsTree() prints the semantics tree, but it prints nothing useful unless you first call tester.ensureSemantics().
Offstage widgets are skipped by default
Finders ignore widgets that are in the tree but offstage. Offstage means the widget is built but not painted, for example in an inactive tab of an IndexedStack. A finder can report zero matches even though debugDumpApp shows the widget. To include offstage widgets, pass skipOffstage: false:
expect(find.text('Hidden tab', skipOffstage: false), findsOneWidget);Use this to check whether the widget exists at all. Do not leave it in as a way to make a test pass, because the real user cannot see offstage content.
Too many matches
find.text('Save') can match the label of a button and a heading with the same text. Narrow the finder instead of picking an index:
- Add a
Keyand usefind.byKey. This is the most stable option. - Use
find.widgetWithText(ElevatedButton, 'Save')to combine type and text. - Use
find.descendant(of: ..., matching: ...)to restrict the search to one subtree.
finder.first, finder.last and finder.at(i) work, but they tie the test to the current widget order. A layout change that reorders widgets then breaks the test for no real reason. Use them only when the order is part of what you are testing.
Missing ancestors and the test window
Widgets that use Theme, MediaQuery, Directionality or Material fail when you pump them alone. Wrap the widget in MaterialApp and Scaffold, as the earlier chapters did. If you test a widget that reads a provider or an inherited widget of your own, add that ancestor to the wrapper too. A helper function that builds the standard wrapper keeps this in one place.
The default test window is 800 by 600 logical pixels at a device pixel ratio of 1.0. A layout that fits on a phone can overflow here, and the reverse also happens. You can set the size yourself and restore it at the end of the test:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('layout works on a narrow phone', (tester) async {
tester.view.physicalSize = const Size(360, 640);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: Row(children: [Expanded(child: Text('A long label'))]),
),
),
);
expect(find.text('A long label'), findsOneWidget);
expect(tester.takeException(), isNull);
});
}tester.takeException() returns the last exception the framework reported and clears it. Layout overflows are reported to the framework, and the test fails at the end if you leave one unhandled. Calling takeException() lets you check for an expected error, or assert that there was none.
pumpAndSettle timeouts
pumpAndSettle keeps pumping frames until no more are scheduled. If something animates forever, it gives up after 10 minutes of fake time and throws pumpAndSettle timed out. The usual cause is a CircularProgressIndicator, a repeating AnimationController, or a periodic Timer that triggers rebuilds.
The fix is to advance time by a fixed amount with pump(Duration) and assert on the state you expect:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('spinner is visible while loading', (tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: Center(child: CircularProgressIndicator())),
),
);
// await tester.pumpAndSettle(); // would time out: the spinner never stops.
await tester.pump(const Duration(milliseconds: 100));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
});
}If a test needs a loaded state, make the fake dependency finish, so the spinner leaves the tree before you settle.
Taps that miss
tester.tap computes the center of the widget and sends a pointer event there. Two situations make it miss:
- The widget is built but scrolled out of view. A
SingleChildScrollViewbuilds all its children, so the finder succeeds, but the position is off the screen. - Another widget covers the target, such as a dialog barrier or an overlay.
Flutter prints a warning that the tap "would not hit test on the specified widget". The test then continues, and your callback never runs, so the failure shows up later as a wrong assertion. Fix it by scrolling the target into view first:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('taps a button below the fold', (tester) async {
var taps = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
const SizedBox(height: 2000),
ElevatedButton(
key: const Key('far'),
onPressed: () => taps++,
child: const Text('Far away'),
),
],
),
),
),
),
);
final button = find.byKey(const Key('far'));
await tester.ensureVisible(button);
await tester.pumpAndSettle();
await tester.tap(button);
await tester.pump();
expect(taps, 1);
});
}Never silence the warning with warnIfMissed: false unless the test is about a tap that is supposed to miss. The warning is telling you the test is not doing what you think.
Stale expectations after a state change
A common mistake is to change state and assert without pumping. setState only marks the widget as dirty. The tree is rebuilt on the next frame, and tester.tap does not produce one for you. After any interaction that changes the UI, call await tester.pump(). Use pump(Duration) or pumpAndSettle if an animation or an async result is involved.
Finders themselves are never stale. A Finder is a description, and it searches the current tree each time you use it. You can create one before the change and reuse it after.
Leftover timers
If the code under test starts a Timer or a Future.delayed that is still pending when the test ends, the test fails with a pending-timer error. Handle it in one of these ways:
- Advance fake time past the timer with
await tester.pump(const Duration(seconds: 1)). - Cancel the timer in
dispose, and make sure the widget is removed from the tree. - Inject a fake that completes immediately, as described in the chapter on fakes.
Narrowing down a large failing test
When a long test fails far from where the real problem started, shrink it:
- Run only that test:
flutter test test/my_widget_test.dart --plain-name "greets the name". - Put
debugDumpApp()after each step and compare the output. - Remove steps from the end until the test passes, then add them back one at a time.
- Once you find the cause, keep the smaller test as a regression test.
Exercise
A test taps a button inside a long ListView, calls await tester.pump(), and then asserts on the result, but the callback never ran. The console shows a warning that tap() "would not hit test on the specified widget". What is the likely cause, and how do you fix it?
Show answer
The button is built but sits outside the visible area of the test window, so the tap lands somewhere else. Scroll it into view first with await tester.ensureVisible(finder) (or scrollUntilVisible for a lazily built list), pump, and then tap. Do not just set warnIfMissed: false.
Exercise
await tester.pumpAndSettle() throws "pumpAndSettle timed out" on a screen that shows a CircularProgressIndicator. Why does it happen, and what do you use instead?
Show answer
The spinner animates continuously, so a new frame is always scheduled and the tree never settles. Use await tester.pump(const Duration(milliseconds: 100)), or another fixed duration, and assert on the state at that point. If you need the loaded UI, make the fake dependency complete so the spinner is removed before you settle.