4

I have a widget defined as follows:

import ...;
...

class TechnicalError extends StatelessWidget {
    ...

    @override
    Widget build(BuildContext context) {
        TechnicalErrorPayload payload = ModalRoute.of(context).settings.arguments;

        return Scaffold(
            body: Column(...)
        );
    }
}

I also have defined a named route for that widget:

import ...;
const String TECHNICAL_DIFFICULTIES = '/technical-difficulties';
class MyApp extends StatelessWidget {

    MyApp() {
        ...
    }

    @override
    Widget build(BuildContext context) {

        return MaterialApp(
            routes: <String, WidgetBuilder> {
            ...
            TECHNICAL_DIFFICULTIES: (BuildContext context) => TechnicalError()
        }

        ...
        );
    }
}

Whenever I want to push that route, I would do as follows:

var techErrPayload = TechnicalErrorPayload(...);
await Navigator.of(context).pushNamed(TECHNICAL_DIFFICULTIES, arguments: techErrPayload);

Everything working as expected. The problem comes when I want to test the TechnicalError widget... How to pass a TechnicalErrorPayload to that widget? It is not part of the constructor. It is being taken by the properties of the ModalRoute.

This won't work:

testWidgets('Me testing', (WidgetTester tester) async {
MaterialPageRoute test = MaterialPageRoute(
  builder: (BuildContext context) => TechnicalError(),

  settings: RouteSettings(
    name: 'Blah',
    arguments: TechnicalErrorPayload(friendlyErrorMessage: 'Hey Joe')
  )
);

//await tester.pumpWidget(WidgetWrapper.fromRouteWithNavigatorObservers(test, [navigatorobserverMock]));

await tester.pumpWidget(
  MaterialApp(
    navigatorObservers: [navigatorobserverMock],
    routes: {
      '/': (BuildContext context) => test.builder(context)
    },

  )
);
await tester.pumpAndSettle();
});
1

1 Answer 1

3

To test a route that uses route arguments I wrapped my screen widget a in a MaterialPageRoute. Then in the route settings I was able to pass any argument the route needed.

await tester.pumpWidget(
  MaterialApp(
    onGenerateRoute: (settings) {
        return MaterialPageRoute(
          settings: RouteSettings(arguments: // Your Argument here),
          builder: (context) {
            return TheScreen();
          },
        );
      },
  )
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.