I'm using the auto_route package in my flutter project and wrapped my App in MaterialApp.router
.
Now I want to test a widget which calls AutoRouter.of(context).pop();
in one place.
My test looks like this:
testWidgets('my widget test',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: MyWidget(),
),
);
});
Pumping the widget understandably throws the following error message:
AutoRouter operation requested with a context that does not include an AutoRouter. The context used to retrieve the Router must be that of a widget that is a descendant of an AutoRouter widget.
So I somehow need to provide an AutoRouter
instance above my widgetin my test.
My widget also uses MediaQuery
and I needed to wrap my tested widget inside MaterialApp
to avoid an error which was thrown due to MediaQuery.of(context)
lookup.
I guess I need to do something similar with AutoRouter
but couldn't figure it out yet. Is there something like a MockAutoRouter
?
Happy for any help.
CodePudding user response:
Okay I got it working.
AutoRouter.of(context)
looks up an instance of StackRouter
which is provided through StackRouterScope
. So I mocked StackRouter
and provided it via StackRouterScope
:
@GenerateMocks([StackRouter])
...
await tester.pumpWidget(
StackRouterScope(
controller: MockStackRouter(),
stateHash: 0,
child: MyWidget(),
),
);
Now AutoRouter.of(context).pop()
does not throw anymore.
It should also be possible now to stub the MockStackRouter
and verify if e.g. pop
is called.