flutter - 如何在使用 http.post 时进行小部件测试
问题描述
我正在尝试对我的项目使用小部件测试,并且测试工作正常,直到达到我在实际页面中使用 http 请求的程度,我认为,忽略该请求
final account = await http.post(
'http://10.0.2.2:5000/LogIn',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode({'email': email, 'password': password}),
);
account.body 在使用模拟器期间运行良好时返回空
testWidgets("Successful Sign In", (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(home: SignIn()));
//1-find widgets needed
final textfieldemail = find.byKey(Key("emailtextformfield"));
expect(textfieldemail, findsOneWidget);
final textfieldpassword = find.byKey(Key("passwordtextformfield"));
expect(textfieldpassword, findsOneWidget);
final buttonsignin = find.byKey(Key("Signin"));
expect(buttonsignin, findsOneWidget);
//2-execute the actual test
await tester.enterText(textfieldemail, "Weaam.wewe91@gmail.com");
await tester.enterText(textfieldpassword, "Weaam@91");
await tester.tap(buttonsignin);
await tester.pump(Duration(seconds: 5));
//await tester.pump(Duration(seconds: 5));
//await _navigateToAccountHome(tester);
//3-check results
expect(find.byType(DeliveryHome), findsOneWidget);
});
});
我不确定我是否错过了什么我还是初学者
解决方案
testWidgets
默认情况下使用 Mocked http 类,该类将始终返回 HTTP 错误 400。这可能是您的代码在模拟器中有效但在测试中无效的原因。
要在测试之前从 Web 服务器前缀/设置中获取实际的 HTTP 响应,请使用:
HttpOverrides.global = null;
例子
由dnfield提供(在 Google Flutter 团队中)。
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
void main() {
setUpAll(() {
// ↓ required to avoid HTTP error 400 mocked returns
HttpOverrides.global = null;
});
testWidgets('http', (WidgetTester tester) async {
await tester.runAsync(() async {
final HttpClient client = HttpClient();
final HttpClientRequest request =
await client.getUrl(Uri.parse('https://google.com'));
final HttpClientResponse response = await request.close();
print(response.statusCode); // Should get 200
});
});
testWidgets('http2', (WidgetTester tester) async {
await tester.runAsync(() async {
final result = await get(Uri.parse('https://google.com'));
print(result.statusCode); // Should get 200
});
});
}
推荐阅读
- php - 当用户单击 php 中的锚标记时如何回显?
- python - 将组件求和为字符串
- python - 调用不带 () 的函数时如何在 Python 中强制出错
- python - numpy rfftn 更改输入尺寸
- javascript - 通过站点 url 将元标记内容值设置为 True
- email - Gmail API 发件人未发送多个附件
- java - 在 Spring Boot 中换行时,语义 UI React 图标显示为空矩形
- python-3.x - 欧洲的 basemap() 中的精确坐标应该是什么?
- css - CSS 垂直对齐和打断文本
- javascript - 按字符串对嵌套对象(多次)进行排序