Skip to content

Instantly share code, notes, and snippets.

@juwencheng
Created August 19, 2018 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juwencheng/ae1f8e2f58ec9c92d2bf0a5d333e27d7 to your computer and use it in GitHub Desktop.
Save juwencheng/ae1f8e2f58ec9c92d2bf0a5d333e27d7 to your computer and use it in GitHub Desktop.
This is a simple example to test a StreamBuilder widget, which data are from http request.
// This is a basic Flutter widget test.
// To perform an interaction with a widget in your test, use the WidgetTester utility that Flutter
// provides. For example, you can send tap and scroll gestures. You can also use WidgetTester to
// find child widgets in the widget tree, read text, and verify that the values of widget properties
// are correct.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:rxdart/rxdart.dart';
import 'package:http/http.dart' as http;
void main() {
Widget snapshotText(BuildContext context, AsyncSnapshot<String> snapshot) {
print(snapshot.toString());
return new Text(snapshot.toString(), textDirection: TextDirection.ltr);
}
Future<Null> eventFiring(WidgetTester tester) async {
await tester.pump(Duration.zero);
}
// create a data stream
final _dataStreamSubject = BehaviorSubject<String>();
Stream<String>_dataStream = _dataStreamSubject.stream;
void refresh() async {
http.Response response = await http.get(
"https://jsonplaceholder.typicode.com/todos/1"
);
if (response.statusCode == 200) {
_dataStreamSubject.add("success");
}else {
_dataStreamSubject.add("failed");
}
}
testWidgets("StreamBuilder from HTTP Request", (WidgetTester tester) async {
await tester.pumpWidget(new StreamBuilder<String>(
stream:_dataStream,
builder: snapshotText
));
await refresh();
eventFiring(tester);
expect(find.text("AsyncSnapshot<String>(ConnectionState.active, true, null)"), findsOneWidget);
});
}
@juwencheng
Copy link
Author

在 testWidgets 方法里面无法添加异步请求方法

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment