首页 > 解决方案 > 颤振自动测试:点击按钮在抽屉中不起作用

问题描述

我正在尝试用颤振做一些 TDD,当测试运行时,如果按钮在抽屉里,点击按钮不起作用。对于普通用户,该按钮可以正常工作。

在下面的示例中,我们按下两个按钮,在控制台中打印一条消息。操作如下:
定位并点击脚手架中的按钮:OK
打开抽屉:OK
定位抽屉中
的按钮:OK 点击抽屉按钮:没有任何反应

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('Test that drawer is apparing and we can click on button',
  (WidgetTester tester) async {
final scaffoldKey = GlobalKey<ScaffoldState>();

await tester.pumpWidget(new MaterialApp(
  title: 'Where Assistant',
  home: Scaffold(
    key: scaffoldKey,
    body: Column(
      children: <Widget>[
        Text('test text'),
        RaisedButton(
          onPressed: () {
            print('OK on main screen');
          },
          child: Icon(Icons.access_alarm),
        ),
      ],
    ),
    drawer: Drawer(
      // Add a ListView to the drawer. This ensures the user can scroll
      // through the options in the Drawer if there isn't enough vertical
      // space to fit everything.
      child: ListView(
        // Important: Remove any padding from the ListView.
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            child: Text('Drawer Header'),
            decoration: BoxDecoration(
              color: Colors.blue,
            ),
          ),
          ListTile(
            title: Text('Item 2'),
            onTap: () {
              // Update the state of the app
              // ...
            },
          ),
          RaisedButton(
            onPressed: () {
              print('OK drawer');
            },
            child: Icon(Icons.add),
          )
        ],
      ),
    ),
  ),
));

await tester.pump();

expect(find.text('test text'), findsOneWidget);
expect(find.byIcon(Icons.access_alarm), findsOneWidget);
await tester.tap(find.byIcon(Icons.access_alarm));
expect(find.byIcon(Icons.add), findsNothing);

scaffoldKey.currentState.openDrawer();
await tester.pump(); // drawer should appear

expect(find.text('Item 2'), findsOneWidget);
expect(find.byIcon(Icons.add), findsOneWidget);
await tester.tap(find.byIcon(Icons.add));
print('end of test');
  });
}

标签: flutter

解决方案


我也遇到了类似的问题。

测试人员能够在抽屉中找到 FlatButton:

expect(find.byType(FlatButton), findsOneWidget);

tester.tap 似乎没有工作:

await tester.tap(find.byType(FlatButton));

但是这个Flutter 问题中提到的解决方案确实有效:

FlatButton button = find.widgetWithText(FlatButton, 'TextExample').evaluate().first.widget;
button.onPressed();

推荐阅读