How to test navigation via Navigator in Flutter

后端 未结 3 1391
走了就别回头了
走了就别回头了 2020-12-16 13:00

Let\'s say, I have a test for a screen in Flutter using WidgetTester. There is a button, which executes a navigation via Navigator. I would like to

3条回答
  •  猫巷女王i
    2020-12-16 14:04

    While what Danny said is correct and works, you can also create a mocked NavigatorObserver to avoid any extra boilerplate:

    class MockNavigatorObserver extends Mock implements NavigatorObserver {}
    

    That would translate to your test case as follows:

    void main() {
      testWidgets('Button is present and triggers navigation after tapped',
          (WidgetTester tester) async {
        final mockObserver = MockNavigatorObserver();
        await tester.pumpWidget(
          MaterialApp(
            home: MyScreen(),
            navigatorObservers: [mockObserver],
          ),
        );
    
        expect(find.byType(RaisedButton), findsOneWidget);
        await tester.tap(find.byType(RaisedButton));
        await tester.pumpAndSettle();
    
        /// Verify that a push event happened
        verify(mockObserver.didPush(any, any));
    
        /// You'd also want to be sure that your page is now
        /// present in the screen.
        expect(find.byType(DetailsPage), findsOneWidget);
      });
    }
    

    I wrote an in-depth article about this on my blog, which you can find here.

提交回复
热议问题