小部件测试无法在抽屉中找到小部件

Widget test cannot find Widget inside a Drawer

我正在尝试创建一个 Widget 测试,它创建一个 Drawer,然后在 Drawer 中查找 Widget。当我运行下面的Widget测试时,响应是:

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

有人知道为什么 Widget 测试没有在抽屉中找到文本 Widget 吗?

如果我使用文本小部件将正文添加到脚手架,则可以按预期找到它。所以它似乎只与抽屉有关。

    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,
      );
    });

首先,当您期待文本时您的抽屉没有打开,因此您将无法找到文本。为此,您需要使用脚手架键打开抽屉。

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,
  );
});