I'm writing a Flutter web application and I want to write a test on the behavior when the user loads the app when he types the URL in the browser's address bar.
For example I would like my test to behave as if the user typed /my/path
.
How can I do that?
If you look at the class PlatformDispatcher
(which olds a singleton instance .instance
) you can see a getter defaultRouteName
.
The route or path that the embedder requested when the application was launched.
This will be the string "
/
" if no particular route was requested.
So when your user starts your application with the url /my/path
, PlatformDispatcher.instance.defaultRouteName
with be equal to '/my/path'
.
You can also access the PlatformDispatcher.instance
from WidgetsBinding.instance.platformDispatcher
and if you read the doc of the getter platformDispatcher
, you'll read:
A subclass of
BindingBase
, such asTestWidgetsFlutterBinding
, can override this accessor to return a differentui.PlatformDispatcher
implementation.
In the context of a testWidgets
testWidgets('', (WidgetTester test) async {});
tester.binding
gives you access to the TestWidgetsFlutterBinding
which is the binding used by widgets library tests. In this test binding, the platformDispatcher
is overridden and a TestPlatformDispatcher
with a setter defaultRouterNameTestValue
that you can use to mock the defaultRouteName
getter.
You can use:
tester.binding.platformDispatcher.defaultRouteNameTestValue = '/my/path'
to test the behavior when the user loads the app when he types the URL /my/path
in the browser's address bar.