Sub topic 16
Testing navigation in widget tests
What a navigation test checks
A navigation test checks that a user action ends on the right screen, with the right data, and that the stack behaves correctly when the user leaves. Widget tests run these checks quickly, with no emulator. They run the real Navigator or Router inside a test harness, so pushes, pops, and redirects behave as they do in the app.
This chapter assumes you can write a basic testWidgets test (pumpWidget, find, expect) and know Navigator.push, pop, named routes, and go_router basics from earlier chapters. For the go_router examples, add go_router to dependencies. For the mocking example, add mocktail to dev_dependencies.
The basic loop: pump, tap, settle, expect
Every navigation test follows the same four steps:
- Build the app with
pumpWidget. The widget must sit under aMaterialAppso aNavigatorexists. - Trigger the action with
tester.tap. - Call
pumpAndSettleso the route transition animation finishes. - Assert with a finder.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const DetailScreen()),
),
child: const Text('Open details'),
),
),
);
}
}
class DetailScreen extends StatelessWidget {
const DetailScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Go back'),
),
),
);
}
}
void main() {
testWidgets('opens details and returns home', (tester) async {
await tester.pumpWidget(const MaterialApp(home: HomeScreen()));
expect(find.byType(DetailScreen), findsNothing);
await tester.tap(find.text('Open details'));
await tester.pumpAndSettle();
expect(find.byType(DetailScreen), findsOneWidget);
await tester.tap(find.text('Go back'));
await tester.pumpAndSettle();
expect(find.byType(DetailScreen), findsNothing);
expect(find.byType(HomeScreen), findsOneWidget);
});
}Without pumpAndSettle, the transition is still running, and both screens may exist at once. A plain pump() advances one frame, so it suits tests that check an in-progress state. If a screen has an infinite animation, such as a progress spinner, pumpAndSettle times out. In that case, use pump(const Duration(milliseconds: 400)), which is longer than the default Material transition.
Checking a result returned by pop
The Future from push completes with the value passed to pop. A test captures it in a variable and asserts after the user finishes the flow. It also covers the back button, which gives null.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class ColorPickerScreen extends StatelessWidget {
const ColorPickerScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Pick a color')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop('red'),
child: const Text('Red'),
),
),
);
}
}
void main() {
Future<void> pumpHost(WidgetTester tester, void Function(String?) onDone) {
return tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: ElevatedButton(
onPressed: () async {
final color = await Navigator.of(context).push<String>(
MaterialPageRoute<String>(
builder: (_) => const ColorPickerScreen(),
),
);
onDone(color);
},
child: const Text('Pick'),
),
),
),
),
);
}
testWidgets('returns the chosen color', (tester) async {
String? result = 'unset';
await pumpHost(tester, (value) => result = value);
await tester.tap(find.text('Pick'));
await tester.pumpAndSettle();
await tester.tap(find.text('Red'));
await tester.pumpAndSettle();
expect(result, 'red');
});
testWidgets('returns null when the user taps back', (tester) async {
String? result = 'unset';
await pumpHost(tester, (value) => result = value);
await tester.tap(find.text('Pick'));
await tester.pumpAndSettle();
await tester.pageBack();
await tester.pumpAndSettle();
expect(result, isNull);
});
}The initial value 'unset' separates "the future never completed" from "it completed with null". tester.pageBack() taps the AppBar back button.
Recording navigation with a NavigatorObserver
Sometimes you care about what the navigator did, not what it drew. A NavigatorObserver that records calls gives you that, and it needs no mocking library. This example also tests onGenerateRoute and its arguments.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class RecordingObserver extends NavigatorObserver {
final List<Route<dynamic>> pushed = [];
final List<Route<dynamic>> popped = [];
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
pushed.add(route);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
popped.add(route);
}
}
Route<dynamic>? onGenerateRoute(RouteSettings settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute<void>(
builder: (_) => const Scaffold(body: Text('Home page')),
settings: settings,
);
case '/details':
final id = settings.arguments as int;
return MaterialPageRoute<void>(
builder: (_) => Scaffold(body: Text('Product $id')),
settings: settings,
);
}
return null;
}
void main() {
testWidgets('pushNamed builds the right route', (tester) async {
final observer = RecordingObserver();
final navigatorKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: navigatorKey,
navigatorObservers: [observer],
onGenerateRoute: onGenerateRoute,
),
);
navigatorKey.currentState!.pushNamed('/details', arguments: 42);
await tester.pumpAndSettle();
expect(find.text('Product 42'), findsOneWidget);
expect(observer.pushed.map((r) => r.settings.name), ['/', '/details']);
expect(observer.pushed.last.settings.arguments, 42);
});
}The first entry, '/', is the initial route. Forgetting it is a common cause of off-by-one assertions. A GlobalKey<NavigatorState> lets the test drive navigation without finding a button first.
Testing a go_router configuration
Test a go_router setup by building the router in a function and handing a fresh instance to each test. Router state is mutable, and sharing one instance leaks the location from one test into the next.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
class AuthNotifier extends ChangeNotifier {
bool _loggedIn = false;
bool get isLoggedIn => _loggedIn;
set isLoggedIn(bool value) {
if (value == _loggedIn) return;
_loggedIn = value;
notifyListeners();
}
}
GoRouter buildRouter(AuthNotifier auth) {
return GoRouter(
refreshListenable: auth,
redirect: (context, state) {
final goingToLogin = state.matchedLocation == '/login';
if (!auth.isLoggedIn && !goingToLogin) return '/login';
if (auth.isLoggedIn && goingToLogin) return '/';
return null;
},
routes: [
GoRoute(
path: '/',
builder: (context, state) => const Scaffold(body: Text('Home screen')),
routes: [
GoRoute(
path: 'products/:id',
builder: (context, state) => Scaffold(
body: Text('Product ${state.pathParameters['id']}'),
),
),
],
),
GoRoute(
path: '/login',
builder: (context, state) => const Scaffold(body: Text('Login screen')),
),
],
);
}
void main() {
testWidgets('guards routes and resolves path parameters', (tester) async {
final auth = AuthNotifier();
final router = buildRouter(auth);
addTearDown(auth.dispose);
addTearDown(router.dispose);
await tester.pumpWidget(MaterialApp.router(routerConfig: router));
await tester.pumpAndSettle();
expect(find.text('Login screen'), findsOneWidget);
auth.isLoggedIn = true;
await tester.pumpAndSettle();
expect(find.text('Home screen'), findsOneWidget);
router.go('/products/42');
await tester.pumpAndSettle();
expect(find.text('Product 42'), findsOneWidget);
});
}Calling router.go directly is a fast way to test deep links, because it does what an incoming URL does. Changing auth.isLoggedIn and settling tests the refreshListenable wiring, which is easy to forget in the app.
Isolating a widget with a mocked GoRouter
When a widget only needs to call context.go, you can test that call without building the whole route tree. InheritedGoRouter makes GoRouter.of(context) return a mock.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:mocktail/mocktail.dart';
class MockGoRouter extends Mock implements GoRouter {}
class ProductTile extends StatelessWidget {
const ProductTile({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ElevatedButton(
onPressed: () => context.go('/products/42'),
child: const Text('View product'),
),
);
}
}
void main() {
testWidgets('tapping the tile navigates to the product', (tester) async {
final router = MockGoRouter();
await tester.pumpWidget(
MaterialApp(
home: InheritedGoRouter(
goRouter: router,
child: const ProductTile(),
),
),
);
await tester.tap(find.text('View product'));
verify(() => router.go('/products/42')).called(1);
});
}This test proves the widget requests the right location. It does not prove the location exists in your router, so keep at least one test against the real configuration.
The back button and PopScope
tester.binding.handlePopRoute() simulates the system back gesture, which reaches PopScope the way a real device would.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('PopScope with canPop false keeps the screen', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: ElevatedButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => const PopScope(
canPop: false,
child: Scaffold(body: Text('Unsaved form')),
),
),
),
child: const Text('Edit'),
),
),
),
),
);
await tester.tap(find.text('Edit'));
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.text('Unsaved form'), findsOneWidget);
});
}Choosing a technique
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `pumpAndSettle timed out` | An endless animation is on screen | Use `pump` with a fixed duration |
| `No Navigator widget found` | Widget pumped without `MaterialApp` | Wrap it in `MaterialApp(home: ...)` |
| Finder sees nothing after a push | Target is offstage | Check the visible screen, or use `skipOffstage: false` |
| `GoRouter.of` fails with "No GoRouter found" | Widget uses `context.go` without a router above it | Use `MaterialApp.router` or `InheritedGoRouter` |
| State leaks between tests | One shared `GoRouter` instance | Create the router inside each test |
Exercise
A test pushes a screen that returns a value on pop. The test taps the AppBar back button and then asserts that the returned value is 'red'. The assertion fails. Why, and how should the test change?
Show answer
The back button pops with no value, so the Future from push completes with null. To get 'red', tap the in-screen button that calls pop('red'). Add a separate test using tester.pageBack() that expects null.
Exercise
A test for a login redirect calls router.go('/') after setting auth.isLoggedIn = true but never calls pumpAndSettle. The expect for the home screen fails. What is missing, and why does pumpWidget alone not cover it?
Show answer
The router resolves the new location and rebuilds the Navigator on later frames. pumpWidget only builds the first frame. The test must call pumpAndSettle (or pump) after changing state or calling go so the redirect, the rebuild, and the transition finish before the assertion.