Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a drawer in flutter test

I am trying to test a custom drawer but find it hard opening it in the test, tried the following to begin with and even this test doesn't pass. The error is: Bad state: no element.

void main() {
  testWidgets('my drawer test', (WidgetTester tester) async {
    final displayName = "displayName";
    var drawKey = UniqueKey();
    await tester.pumpWidget(MaterialApp(
        home: Scaffold(
      drawer: Drawer(key: drawKey, child: Text(displayName),),
    )));
    await tester.tap(find.byKey(drawKey));
    expect(find.text(displayName), findsOneWidget);
  });
}
like image 539
stt106 Avatar asked Nov 14 '18 11:11

stt106


People also ask

How do you show the drawer in Flutter?

The navigation drawer is added using the Drawer widget. It can be opened via swipe gesture or by clicking on the menu icon in the app bar. Typically, the navigation drawer opens up from the left side of the screen, but you can also configure it to open from the right side (for the LTR text settings).

How do I know if my Flutter drawer is open?

You can simply use onDrawerChanged for detecting if the drawer is opened or closed in the Scaffold widget.

How do I close the Flutter drawer?

To close the drawer, use either ScaffoldState. closeDrawer, Navigator. pop or press the escape key on the keyboard. To disable the drawer edge swipe on mobile, set the Scaffold.


1 Answers

You're calling tap() on the Drawer, but it isn't in view as it's hidden on the left. Because of this, the Finder doesn't find any elements and the tap() is unsuccessful. And even if the Finder found the Drawer, tapping on the Drawer itself doesn't open it anyway.

One way, and in my opinion, the simplest way of doing it is to provide a GlobalKey for the Scaffold and call openDrawer() on the current State of it. You could also tap on the hamburger icon or swipe from the left - but calling openDrawer() is more deterministic:

void main() {
  testWidgets('my drawer test', (WidgetTester tester) async {
    final scaffoldKey = GlobalKey<ScaffoldState>();
    const displayName = "displayName";

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          key: scaffoldKey,
          drawer: const Text(displayName),
        ),
      ),
    );

    scaffoldKey.currentState.openDrawer();
    await tester.pump();

    expect(find.text(displayName), findsOneWidget);
  });
}
like image 50
Iiro Krankka Avatar answered Nov 22 '22 20:11

Iiro Krankka