我想知道如何在flutter小部件测试中完成未完成的情况时进行测试。
只要未来未解决,小部件就应显示微调框。
我整理了这个测试用例:
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使用本地化初始化一个App。因此,我必须致电tester.pumpAndSettle()
等待l10n。
答案 0 :(得分: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正常运行。
答案 1 :(得分:0)
我找到了一个使用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);
},
);
答案 2 :(得分: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);
},
);