flutter widget testing - how to execute test to "Go Back to Prevoius Screen"
Asked Answered
S

3

7

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.

Skees answered 31/8, 2018 at 3:5 Comment(8)
docs.flutter.io/flutter/flutter_test/WidgetTester/pageBack.htmlShea
Thank you for quick response. Any sample code to refer?Skees
@GünterZöchbauer This test whether there is a button, but not if the route was actually popped.Konrad
#50705147Shea
I used *tester.pumpAndSettle() * after entering into page then tried tester.goBack() and it worked. Thank you @Günter ZöchbauerSkees
Glad to hear. You could answer your own question with your solution.Shea
@GünterZöchbauer when I use tester.pageBack() , I get an error zero widgets with type "CupertinoNavigationBarBackButton" (this is in widget test) phonePage = MediaQuery( data: MediaQueryData(), child: MaterialApp( home: PhonePage(), navigatorObservers: [observer], ), );Nerval
@Nerval I face the same error. Did you solve it?Goosy
B
1

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 property navigatorObservers: [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();
    
Balfour answered 2/7, 2020 at 10:49 Comment(0)
E
0

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

Emsmus answered 22/7 at 19:19 Comment(0)
S
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);
Scat answered 11/8 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.