'How do I verify an alert dialog has appeared using mockingjay in a widget test?

Using the mockingjay Flutter package, how do I verify in a widget test that an alert dialog has been displayed after e.g. tapping a button? The alert dialog is displayed using the showDialog function.



Solution 1:[1]

This is very similar to verifying page navigation behaviour, the thing that caught me out was the showDialog function must have the parameter useRootNavigator set to false, as documented in the example project. Without it the test will fail to detect that the alert dialog was displayed.

showDialog(
   context: context,
   useRootNavigator: false, // By default this is true, which won't work with Mockingjay
   routeSettings: RouteSettings(name: 'verify_checkout_failure'),
   builder: (context) {
       return AlertDialog(title: Text('Checkout failed'));
   });

Then in your test:

await tester.tap(find.byType(PlaceOrderButton));

  verify(
    () => mockNavigator.push(
      any(
        that: isRoute<void>(
          whereName: equals('verify_checkout_failure'),
        ),
      ),
    ),
  );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris Wickens