Sometimes you need to make sure your Flutter app's navigation is working correctly, especially with GoRouter.
Testing widgets directly is often simpler, but testing navigation flow can be useful for certain scenarios.
How to Test GoRouter Navigation
Here’s a simple way to set up tests for your GoRouter navigation:
Steps
- Embed your router within a Material app: Wrap your GoRouter setup inside a
MaterialApp.router
. This provides the necessary context for navigation. - Add your pages within routes: Define the routes and the widgets (pages) they lead to in your
GoRouter
configuration. - Run your app within your test: Use
testWidgets
to pump yourMaterialApp.router
widget into the test environment. - Check your expectations: Use
expect
to verify the widgets or content that should appear after navigation, or test specific behaviors like redirects.
Additional Tip
To test specific parts of your navigation or start your test from a particular screen, you can pass an initialLocation
parameter when creating your GoRouter
. Embedding the router creation logic within a function that accepts initialLocation
makes this flexible for tests.