routemaster
routemaster copied to clipboard
How to test widget which calls Routemaster.of(context)?
I have a widget containing a button which navigates using routemaster:
ElevatedButton(
child: const Text("Do Something"),
onPressed: () {
// Do some things ...
Routemaster.of(context).push("/route2");
},
)
Then, in my widget tests for the widget:
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
However, this will throw an error since the build context has no routemaster in the test widget:
'package:routemaster/routemaster.dart': Failed assertion: line 141 pos 7: 'widget != null': Couldn't get a Routemaster object from the given context.
Is there a way to mock/stub Routemaster for use in widget tests like this?
Hi, I'd suggest just wrapping your test widgets in a MaterialApp
with a Routemaster setup, that's what I do. I always prefer using real dependencies and only mocking when absolutely necessary.
If you don't want to use your real routing setup in the test, you can always inject a fake home route which has just the widget you want to test.