首页 > 解决方案 > 如何等到 Finder 在 Flutter 集成测试中显示下一个代码执行?

问题描述

信息:
我创建了一个示例 Flutter 单元测试来测试登录屏幕,其中我有电子邮件和密码作为输入字段和一个登录按钮。

要求:
需要测试虚假案例,为此,我已按照以下步骤编写代码。

  1. 打开 main.dart
  2. 填写电子邮件和密码字段
  3. onTap 事件在登录按钮上完成。在这里将调用 API 并在屏幕上显示加载程序,直到 API 获得成功或失败响应。
  4. 需要检查是否显示失败对话框并显示消息。

问题/查询:
现在,当 API 调用时,我想等待加载器可见,直到加载器消失。所以,到目前为止,我只是手动延迟执行下一个代码,但我想让它动态化。那么,让我知道我们如何根据加载程序显示动态延迟?

代码:

void main() {
  group('App Test', () {
    IntegrationTestWidgetsFlutterBinding.ensureInitialized();

    testWidgets('Login Fail Test', (WidgetTester tester) async {
      await app.main();
      await tester.pumpAndSettle();

      await tester.pump(new Duration(seconds: 2));

      final emailField = find.byType(TextFormField).first;
      final passwordField = find.byType(TextFormField).last;
      final loginButton = find.byType(RaisedButton).first;

      await tester.enterText(emailField, 'Test');
      await tester.pumpAndSettle();
      await tester.pump(new Duration(seconds: 1));

      await tester.enterText(passwordField, 'Test123');
      await tester.pumpAndSettle();
      await tester.pump(new Duration(seconds: 1));

      await tester.tap(loginButton);
      await tester.pumpAndSettle();
      await tester.pump(new Duration(seconds: 3));

     
      final dialog = find.byType(AlertDialog).first;
      await tester.element(dialog);
      await tester.pumpAndSettle();
      await tester.pump(new Duration(seconds: 1));

      final dialogButton = find.byType(FlatButton).first;
      await tester.tap(dialogButton);
      await tester.pumpAndSettle();
      await tester.pump(new Duration(seconds: 2));
    });
}

标签: flutterunit-testingdartflutter-integration-test

解决方案


尝试像这样包装:

testWidgets('test',
    (WidgetTester tester) async {
    await tester.runAsync(() async {

      // test code here

    });
 });

如果您使用:

await tester.pumpAndSettle();

接着:

  final widget = find.byKey(Key('whatever'));

它会动态地找到


推荐阅读