flutter - Flutter:导航在应用程序中有效,但在单元测试中无效
问题描述
导航在实际应用程序中适用于我,但不适用于单元测试。
这有效(点击“Go to page2”导航到/page2
):
runApp(
MaterialApp(
routes: {
"/": (BuildContext context) => Scaffold(
body: Column(
children: [
Text("Home"),
TextButton(
onPressed: () {
print("pressed [Go to page2]");
Navigator.pushReplacementNamed(context, "/page2");
},
child: Text("Go to page2"),
)
]
)
),
"/page2": (BuildContext context) => Scaffold(
body: Text("Page 2")
),
},
)
);
但是当我在单元测试中尝试这个确切的代码并假装点击按钮时 - 我确实在控制台中看到消息“按下 [转到第 2 页]”,所以我知道按钮被点击了,但导航本身似乎没有发生是因为在页面上找不到文本“第 2 页”:
testWidgets("Test", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
routes: {
"/": (BuildContext context) => Scaffold(
body: Column(
children: [
Text("Home"),
TextButton(
onPressed: () {
print("pressed [Go to page2]");
Navigator.pushReplacementNamed(context, "/page2");
},
child: Text("Go to page2"),
)
]
)
),
"/page2": (BuildContext context) => Scaffold(
body: Text("Page 2")
),
},
)
);
expect(find.text("Home"), findsOneWidget); // Passes
await tester.tap(find.byType(TextButton)); // Correctly prints "pressed [Go to page2]"
await tester.pump(Duration(seconds: 10));
expect(find.text("Home"), findsOneWidget); // Passes
expect(find.text("Page 2"), findsOneWidget); // FAILS!!
});
我究竟做错了什么?
为什么此代码在实际应用程序中有效,但在单元测试中无效?
解决方案
推荐阅读
- android - 提供的主题值无效 - 将 FCM 发送到主题时
- wso2 - 数据服务字段的 wso2 数据服务过滤器为空
- spring - spring boot:无法绑定yaml列表对象
- python - PIP 格式的差异
- asp.net - 使用 BaseController 时的 ASP.NET Core MVC 应用程序依赖注入问题
- ios - NSDate 变量持久化
- c# - 按钮播放器首选项
- plugins - Eclipse CDT 插件 - 仅限于函数名称的操作
- c# - Web API + Azure App Insights 将数据从 ActionFilter 传递到 ITelemetryProcessor
- javascript - 仅在 IE 中找不到模块“反应”