I am writing widget tests in Flutter. I am not able to find any documentation to execute "Go Back to Prevoius Screen" as I do not find any method for that. Please help with some sample "test" code for the same.
flutter widget testing - how to execute test to "Go Back to Prevoius Screen"
Asked Answered
You have to mock navigation observer.
First create class
class MockNavigatorObserver extends Mock implements NavigatorObserver
Declare
final mockObserver = MockNavigatorObserver();
in your test file.Put your widget inside
MaterialApp
and add propertynavigatorObservers: [mockObserver],
Finally inside your testWidgets block {} mock like this:
final mockObserver = MockNavigatorObserver(); final backIcon = find.byIcon(Icons.arrow_back_ios); expect(backIcon, findsOneWidget); await tester.tap(backIcon); verify(mockObserver.didPop(any, any)); await tester.pumpAndSettle();
You can add a global navigatorKey to the material app of your tests. Then use that to pop the current screen
For example
testWidgets(
'someMethodCalledOnPop is invoked with someValue on back pressed',
(WidgetTester tester) async {
final navigatorKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: navigatorKey,
home: MyWidget(),
),
),
);
navigatorKey.currentState!.pop();
verify(someMethodCalledOnPop("someValue"))
});
... rest of test
This is on flutter 3.22.2. mockito: ^5.3.0
As of Flutter v.3.22.3, I've found looking for the Type, BackButton, gets you back to the previous screen:
final backButton = find.byType(BackButton);
expect(backButton, findsOneWidget,
reason: 'One back button expected on screen');
await tester.tap(backButton);
© 2022 - 2024 — McMap. All rights reserved.
phonePage = MediaQuery( data: MediaQueryData(), child: MaterialApp( home: PhonePage(), navigatorObservers: [observer], ), );
– Nerval