测试CircularProgressIndicator

11

我正在使用 ModalProgressHud 显示一个旋转图标,以便在等待服务器响应时等待。 我想测试当用户点击按钮时是否会显示 CircularProgressIndicator。 我的问题是,pumpAndSettle() 会超时,因为这个 CircularProgressIndicator ,我认为它不断地重建自己。 有什么建议可以测试是否存在 CircularProgressIndicator吗? 这是我的测试:

testWidgets(
      'Should show a CircularProgressIndicator while it tries to login', (WidgetTester tester) async {

    await (tester.pumpWidget(
             generateApp(LoginView())
          ));
    await tester.pumpAndSettle();
    await tester.tap(find.byType(FlatButton));
    await tester.pumpAndSettle();

    expect(find.byType(CircularProgressIndicator), findsOneWidget);
  });
3个回答

8

你的想法是正确的 - 你不能使用pumpAndSettle,因为CircularProgressIndicator会无限地执行动画。你可以尝试使用带有超时的tester.pump()来代替pumpAndSettle


3

如果您将来需要实现Golden测试,本答案可以帮到您。

正如MichaelM所说,您应该使用tester.pump()而不是tester.pumpAndSettle()。我不想重复这个答案,但是要让您知道,在进行Golden测试时,如果您想测试进度指示器或其他动画小部件,您应该将pump设置为Golden测试的泵类型,因为默认情况下它设置为pumpAndSettle,测试会失败。

await screenMatchesGolden(
  tester,
  'loading_page',
  // The custom pump (tester.pump) only show a frame of
  // a never-ended animation like `CircularProgressIndicator`,
  // otherwise the default pump (tester.pumpAndSettle) waits
  // until the animation ends (infinite) and it timeouts.
  customPump: (tester) async => await tester.pump(
    // We need to provide a duration to make the fake timer
    // advance, otherwise it remains on the 0 time slot and
    // raises an exception.
    const Duration(milliseconds: 20),
  ),
);


0
你应该创建一个“loading”布尔值,并在登录屏幕之前使用setState((){}),以及在评估登录是否成功时使用另一个。
我不确定如何按照你的代码进行操作,但可能是这样的...
bool loading = false;

testWidgets(
      'Should show a CircularProgressIndicator while it tries to login', (WidgetTester tester) async {

    loading == false ? setState((){
             loading = true;
             await (tester.pumpWidget(
             generateApp(LoginView())
          ));}
    await tester.pumpAndSettle();
    await tester.tap(find.byType(FlatButton));
    await tester.pumpAndSettle();

    expect(find.byType(CircularProgressIndicator), findsOneWidget);
  });

你如何在这里使用setState? - Little Monkey
在我上面的示例中,我使用了if语句/三元运算符来确定“loading”的状态,然后将状态设置为loading = true,呈现您的CircularProgressIndicator,并呈现登录屏幕。成功登录后,将状态设置为loading = false,关闭ProgressIndicator,并导航到下一个屏幕。 - Charles Jr
你的示例中setState未定义。 - spkersten
最好使用BLoC模式或类似的设计来分离状态和视图。这将使小部件的测试更加容易。教程 - Ber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接