Home > Software engineering >  Widget test cannot find Widget inside a Drawer
Widget test cannot find Widget inside a Drawer

Time:12-28

I am trying to create a Widget test that creates a Drawer and then finds Widgets within the Drawer. When I run the following Widget test, the response is:

Expected: exactly one matching node in the widget tree Actual: _KeyFinder:<zero widgets with key [<'test'>]> Which: means none were found but one was expected

Anyone have any idea why the Widget test is not finding the Text Widget inside the Drawer?

If I add a body to the Scaffold with a Text Widget then that is found as expected. So it only seems to be with the Drawer.

    testWidgets('shows drawer', (WidgetTester tester) async {
      await tester.pumpWidget(
        const MaterialApp(
          home: Scaffold(
            drawer: Drawer(
                child: Text(
              'test',
              key: Key('test'),
            )),
          ),
        ),
      );
      await tester.pumpAndSettle();
      expect(
        find.byKey(const Key('test'), skipOffstage: false),
        findsOneWidget,
      );
    });

CodePudding user response:

First of all, your drawer is not open at the time when you are expecting a text and hence you will not able to find text. To do this, you need to open drawer using scaffold key.

final _scaffoldKey = GlobalKey<ScaffoldState>();
testWidgets('shows drawer', (WidgetTester tester) async {
  await tester.pumpWidget(
  MaterialApp(
    home: Scaffold(
      key: _scaffoldKey,
      drawer: Drawer(
          child: Text(
        'test',
         key: Key('test'),
       )),
     ),
   ),
 );
  _scaffoldKey.currentState!.openDrawer();
  await tester.pumpAndSettle();
  expect(
    find.byKey(const Key('test'), skipOffstage: false),
    findsOneWidget,
  );
});
  • Related