flutterflutter-webflutter-testflutter-web-browser

How to simulate the behaviour when the user loads the app from the URL in the browser's address bar


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?


Solution

  • 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'.


    How to mock it?

    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 as TestWidgetsFlutterBinding, can override this accessor to return a different ui.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.

    TL;DR

    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.