如何在颤动测试中打开抽屉

How to open a drawer in flutter test

我正在尝试测试一个自定义抽屉,但发现在测试中很难打开它,尝试了以下开始,但即使这个测试也没有通过。错误是: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);
  });
}

您正在 Drawer 上呼叫 tap(),但它隐藏在左侧,因此不可见。因此,Finder 没有找到任何元素并且 tap() 不成功。即使 Finder 找到了 Drawer,点击 Drawer 本身也不会打开它。

一种方法,在我看来,最简单的方法是为 Scaffold 提供 GlobalKey 并在当前 State 上调用 openDrawer()它的。您也可以点击汉堡包图标或从左侧滑动 - 但调用 openDrawer() 更具确定性:

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

您可以抓住父窗口小部件的左上角并使用 dragFrom 来模拟打开抽屉。与当前接受的答案相比,这不需要您传递脚手架密钥。

对原代码稍作修改的例子:

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.dragFrom(tester.getTopLeft(find.byType(MaterialApp)), Offset(300, 0));
  await tester.pumpAndSettle();

  expect(find.text(displayName), findsOneWidget);
});

添加了通知 tester.pumpAndSettle() 以确保已经过了足够的时间。

另一种解法:

  final ScaffoldState state = tester.firstState(find.byType(Scaffold));
  state.openDrawer();
  await tester.pump();
  await tester.tap(find.byTooltip('your tooltip text'));
  await tester.pump();