gpt4 book ai didi

flutter - 如何测试Flutter中流有延迟的StreamBuilder?

转载 作者:IT王子 更新时间:2023-10-29 07:05:55 27 4
gpt4 key购买 nike

我有一个有延迟的流。 StreamBuilder 永远不会从测试中的流中获取值“foo”。如果删除延迟,则测试将按预期进行。我如何告诉测试等待这个延迟?

testWidgets('stream builder', (tester) async {
final textKey = Key('textKey');
final stream = Observable.just('foo').delay(Duration(milliseconds: 1));

var app = MaterialApp(
home: StreamBuilder<String>(
stream: stream,
builder: (context, snapshot) => Text(
snapshot.data ?? 'no data',
key: textKey,
),
),
);

await tester.pumpWidget(app);
await tester.pump(Duration.zero);

Text text = tester.widget(find.byKey(textKey));
expect(text.data, equals('foo'));
});

失败并出现错误

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞══════════════════════════
The following TestFailure object was thrown running a test:
Expected: 'foo'
Actual: 'no data'
Which: is different.
Expected: foo
Actual: no data
^
Differ at offset 0

最佳答案

找到解决方案。诀窍是将它包装在 tester.runAsync() 中,我还必须添加 tester.idle()

testWidgets('stream builder', (tester) async {
final textKey = Key('textKey');

await tester.runAsync(() async { // IMPORTANT
final stream = Observable.just('foo').delay(Duration(milliseconds: 1));

var app = MaterialApp(
home: StreamBuilder<String>(
stream: stream,
builder: (context, snapshot) => Text(
snapshot.data ?? 'no data',
key: textKey,
),
),
);

await tester.pumpWidget(app);
await tester.idle(); // IMPORTANT
await tester.pump(Duration.zero); // IMPORTANT
});

Text text = tester.widget(find.byKey(textKey));
expect(text.data, equals('foo'));
});

关于flutter - 如何测试Flutter中流有延迟的StreamBuilder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52911008/

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