gpt4 book ai didi

Flutter 小部件测试 - 等待 Future 完成

转载 作者:行者123 更新时间:2023-12-05 03:03:37 25 4
gpt4 key购买 nike

我在 flutter 中有一个 widget 测试,可以抽取被测 widget,当它打开时,执行后台操作 (staticWrapper.requestPermission()),该操作返回 Future 并根据其结果设置状态。问题是测试没有等待这个 future 完成,测试代码:

/// When micro permission denied, should show error message.
testWidgets('When micro permission denied, should show error message.',
(WidgetTester tester) async {
when(staticWrapper.requestPermission(Permission.RecordAudio))
.thenAnswer((_) => Future.value(PermissionStatus.denied));
await tester.pumpWidget(widget);
final loginText = find.text(callScreen_microPermissionDenied);
expect(loginText, findsOneWidget);
});

受影响的小部件代码:

void _requestMicroPermission() async {
final result =
await staticWrapper.requestPermission(Permission.RecordAudio);
debugPrint("Microphone permission status: $result");
if (result == PermissionStatus.authorized) {
native.init();
} else {
setState(() {
_loginText = tnsManager.getText(TranslationsManager.callScreen_microPermissionDenied);
});
}

expect() 方法在 setState() 调用之前被调用。

有什么帮助吗?

最佳答案

最后我使用 WidgetTester#pumpAndSettle() 解决了这个问题:

testWidgets('When micro permission denied, should show error message.',
(WidgetTester tester) async {
when(staticWrapper.requestPermission(Permission.RecordAudio))
.thenAnswer((_) => Future.value(PermissionStatus.denied));
await tester.pumpWidget(widget);
await tester.pump();
final loginText = find.text(callScreen_microPermissionDenied);
expect(loginText, findsOneWidget);
});

关于Flutter 小部件测试 - 等待 Future 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53671841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com