5

我想知道如何在颤振小部件测试中尚未完成未来的情况下测试该案例。

只要未来未解决,小部件就应该显示一个微调器。

我尝试了这个测试用例:

testWidgets(
  'should show a spinner when loading',
  (WidgetTester tester) async {
    when(valueRepository.getValues())
        .thenAnswer((_) => Future.delayed(Duration(seconds: 30), () => []));
    await tester.pumpWidget(withApp(ValueListPage(
      valueRepository: valueRepository,
    )));

    await tester.pumpAndSettle(
        Duration(seconds: 10), EnginePhase.build, Duration(minutes: 1));

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

结果:未来已解决,期望落空。

注意: withApp 初始化一个带有本地化的应用程序。因此,我必须打电话tester.pumpAndSettle()等待l10n。

4

3 回答 3

2

我找到了一个使用 fakeAsync 的可行解决方案:

testWidgets(
  'should show a spinner when loading',
  (WidgetTester tester) async {
      when(valueRepository.getValues()).thenAnswer(
          (_) => Future.delayed(Duration(seconds: 1), () => []));
      await tester.pumpWidget(withApp(ValueListPage(
        valueRepository: valueRepository,
      )));

      await tester.pump();

      expect(find.byType(CircularProgressIndicator), findsOneWidget);
      await tester.pumpAndSettle();
      expect(find.byType(CircularProgressIndicator), findsNothing);
  },
);
于 2018-09-24T12:42:47.910 回答
1

尝试

testWidgets(
  'should show a spinner when loading',
  (WidgetTester tester) async {
    tester.runAsync(() async {
      when(valueRepository.getValues())
          .thenAnswer((_) => Future.delayed(Duration(seconds: 30), () => []));
      await tester.pumpWidget(withApp(ValueListPage(
        valueRepository: valueRepository,
      )));

      await tester.pumpAndSettle(
          Duration(seconds: 10), EnginePhase.build, Duration(minutes: 1));

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

默认情况下使用 fakeAsync 运行测试,并且某些异步代码无法使用 fakeAsync 正常运行。

于 2018-09-24T06:57:35.967 回答
0

尝试使用完成程序来保持 AsyncSnapshot 处于等待状态。例如:

testWidgets('should show a spinner when loading',(WidgetTester tester) async {

    Completer completer = Completer();
    when(valueRepository.getValues())
       .thenAnswer((_) => completer.future);
    await tester.pumpWidget(withApp(ValueListPage(
    valueRepository: valueRepository,
    )));

    expect(find.byType(CircularProgressIndicator), findsOneWidget); 
 },
);
于 2019-12-17T19:48:05.223 回答