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

时间:2018-11-14 11:23:57

标签: flutter 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);
  });
}

2 个答案:

答案 0 :(得分:6)

您正在呼叫tap()上的Drawer,但由于它隐藏在左侧,所以它不在视野中。因此,Finder找不到任何元素,并且tap()不成功。而且即使Finder找到了Drawer,点击Drawer本身也无法将其打开。

一种方法(在我看来,最简单的方法是为GlobalKey提供Scaffold并在当前openDrawer()上调用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);
  });
}

答案 1 :(得分:0)

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