我的流中有延迟。在测试中,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
答案 0 :(得分: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'));
});