7

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

2 回答 2

15

您正在调用tap()Drawer但它不在视图中,因为它隐藏在左侧。因此,Finder没有找到任何元素并且tap()不成功。即使Finder找到了Drawer,点击它Drawer本身也不会打开它。

一种方法,在我看来,最简单的方法是提供一个GlobalKeyfor theScaffold并调用openDrawer()它的 current State。您也可以点击汉堡图标或从左侧滑动 - 但呼叫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);
  });
}
于 2018-11-14T11:43:04.737 回答
5

您可以抓住父小部件的左上角并使用 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() 以确保已经过去了足够的时间。

于 2020-02-16T20:55:14.540 回答