Sub topic 17
Testing routes and redirects
This chapter assumes you can write a basic Flutter widget test with testWidgets and pumpWidget. It also assumes you know the GoRouter setup from the earlier chapters: redirect, refreshListenable, nested routes, and errorBuilder.
What to test
A router configuration holds logic: which screen a URL maps to, which users may see it, and what happens on an unknown path. Testing that logic catches mistakes before a user hits a redirect loop.
| What you check | Test type | How |
|---|---|---|
| Redirect decision rules | Unit test | Call a plain Dart function |
| Location after navigation | Widget test | Read the router's current URI |
| Visible screen | Widget test | `find.text` or `find.byType` |
| Back stack | Widget test | `router.canPop()` and `router.pop()` |
Make the router testable
Tests are hard to write against a global final GoRouter router. Every test would share its location, and its auth state would leak between tests. Use two changes instead:
- Build the router in a function that receives its dependencies.
- Move the redirect rule into a pure function with no
BuildContextand noGoRouterState.
This is lib/app_router.dart. The tests below assume your package is named my_app.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthState extends ChangeNotifier {
AuthState({bool loggedIn = false}) : _loggedIn = loggedIn;
bool _loggedIn;
bool get loggedIn => _loggedIn;
void logIn() {
_loggedIn = true;
notifyListeners();
}
void logOut() {
_loggedIn = false;
notifyListeners();
}
}
/// Returns the location to redirect to, or null to stay where we are.
String? authRedirect({required bool loggedIn, required String location}) {
final bool atLogin = location == '/login';
if (!loggedIn) {
return atLogin ? null : '/login';
}
return atLogin ? '/' : null;
}
GoRouter buildRouter(AuthState auth) {
return GoRouter(
initialLocation: '/',
refreshListenable: auth,
redirect: (context, state) => authRedirect(
loggedIn: auth.loggedIn,
location: state.matchedLocation,
),
errorBuilder: (context, state) => const Text('Not found'),
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const Text('Home'),
routes: <RouteBase>[
GoRoute(
path: 'books/:id',
builder: (context, state) =>
Text('Book ${state.pathParameters['id']}'),
),
],
),
GoRoute(
path: '/login',
builder: (context, state) => const Text('Login'),
),
],
);
}buildRouter creates a new router per call, so each test starts clean. The redirect callback only forwards two values to authRedirect, so the decision logic can be checked without Flutter.
Write the tests
The widget tests need two helpers. pumpApp mounts the router and waits for the first navigation to finish. currentPath reads the location the router has settled on.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:my_app/app_router.dart';
String currentPath(GoRouter router) =>
router.routerDelegate.currentConfiguration.uri.path;
Future<GoRouter> pumpApp(WidgetTester tester, AuthState auth) async {
final GoRouter router = buildRouter(auth);
await tester.pumpWidget(MaterialApp.router(routerConfig: router));
await tester.pumpAndSettle();
return router;
}
void main() {
group('authRedirect', () {
test('sends signed-out users to /login', () {
expect(authRedirect(loggedIn: false, location: '/books/1'), '/login');
});
test('keeps signed-out users on /login', () {
expect(authRedirect(loggedIn: false, location: '/login'), isNull);
});
test('sends signed-in users away from /login', () {
expect(authRedirect(loggedIn: true, location: '/login'), '/');
});
test('leaves signed-in users alone elsewhere', () {
expect(authRedirect(loggedIn: true, location: '/books/1'), isNull);
});
});
group('router', () {
testWidgets('signed-out start lands on login', (tester) async {
final GoRouter router = await pumpApp(tester, AuthState());
expect(currentPath(router), '/login');
expect(find.text('Login'), findsOneWidget);
});
testWidgets('deep link is blocked when signed out', (tester) async {
final GoRouter router = await pumpApp(tester, AuthState());
router.go('/books/42');
await tester.pumpAndSettle();
expect(currentPath(router), '/login');
});
testWidgets('logging in re-runs the redirect', (tester) async {
final AuthState auth = AuthState();
final GoRouter router = await pumpApp(tester, auth);
auth.logIn();
await tester.pumpAndSettle();
expect(currentPath(router), '/');
expect(find.text('Home'), findsOneWidget);
auth.logOut();
await tester.pumpAndSettle();
expect(currentPath(router), '/login');
});
testWidgets('path parameter reaches the screen and back works',
(tester) async {
final GoRouter router =
await pumpApp(tester, AuthState(loggedIn: true));
router.go('/books/42');
await tester.pumpAndSettle();
expect(find.text('Book 42'), findsOneWidget);
expect(router.canPop(), isTrue);
router.pop();
await tester.pumpAndSettle();
expect(find.text('Home'), findsOneWidget);
});
testWidgets('unknown location shows the error screen', (tester) async {
final GoRouter router =
await pumpApp(tester, AuthState(loggedIn: true));
router.go('/nope');
await tester.pumpAndSettle();
expect(find.text('Not found'), findsOneWidget);
});
});
}Run it with flutter test.
Why each test is shaped this way
The unit tests cover every branch of the redirect rule in milliseconds. If you keep rules like these out of the widget tree, most of your coverage runs without a widget tree.
The widget tests then check the wiring. They confirm that refreshListenable is connected, that nested routes build, and that errorBuilder runs.
The test asserts on the location and on the visible widget. The location proves the router decided correctly. The widget proves the route table points at the right screen.
router.go and router.pop are called directly, so the tests do not need to tap buttons. Tapping a button is worth one test when the button's callback is the thing at risk, for example a typo in a path string.
Common errors
- Forgetting to pump after a state change.
auth.logIn()only schedules work. WithoutpumpAndSettle, the location is still the old one. pumpAndSettletiming out. This happens when something animates forever, such as aCircularProgressIndicatoron the screen. Usetester.pump(const Duration(milliseconds: 300))for those screens.- Sharing one router across tests. The location persists, so a test passes or fails depending on run order. Build the router in each test.
- Redirect loops. If two rules send users to each other's targets, go_router stops after its redirect limit (5 by default) and shows the error screen. A unit test of the redirect function for each location and each auth state finds the loop before a user does.
- Asserting on text that is covered. After a push, the page below is offstage.
find.text('Home')skips offstage widgets by default, so it returns nothing. AddskipOffstage: falseonly if you really want to check hidden pages.
Exercise
A test calls auth.logOut() and then immediately expects currentPath(router) to equal '/login', but the expectation fails. What is missing, and why?
Show answer
The test needs await tester.pumpAndSettle() between logOut() and the expectation. notifyListeners only tells the router to re-run its redirect. The router applies the new location and rebuilds the widget tree during the next frame, which a pump triggers.
Exercise
You add a /admin route that only users with an isAdmin flag may open, and everyone else is sent to '/'. Extend authRedirect and write two unit tests for it.
Show answer
Add an isAdmin parameter, defaulting to false. After the existing login checks, return '/' when location.startsWith('/admin') && !isAdmin. Tests: authRedirect(loggedIn: true, isAdmin: false, location: '/admin') returns '/', and authRedirect(loggedIn: true, isAdmin: true, location: '/admin') returns null.