flutter - Dart/flutter 小部件测试,无论是按键还是文本都找不到文本小部件
问题描述
我在 ResoCoder 示例中使用 WeatherAPI 实现了一个应用程序。我现在想测试每个文本小部件是否显示正确的信息,但我已经找不到文本小部件(我使用了本指南https://resocoder.com/2021/01/02/flutter-integration-test-tutorial-firebase -test-lab-codemagic/)。我通过使用 find.byKey() (当然之前设置了一些键)和 find.byText() 进行了尝试,但没有一个起作用。
我的测试代码:
testWidgets('Infos are displayed', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(home: WeatherScreen()));
await tester.pump();
final tempField = find.byKey(ValueKey("temperature"));
expect(tempField, findsOneWidget);
expect(find.text('humidity'), findsOneWidget);
});
我总是收到没有找到那些小部件的错误:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
Expected: exactly one matching node in the widget tree
Actual: _KeyFinder:<zero widgets with key [<'temperature'>] (ignoring offstage widgets)>
Which: means none were found but one was expected
还有我的屏幕小部件:
class WeatherScreen extends StatelessWidget {Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: BlocBuilder<WeatherCubit, WeatherBaseState>(
bloc: WeatherCubit(weatherRepository: WeatherRepository())..getWeather(),
builder: (context, state) {
if (state is LoadingWeather) {
return CircularProgressIndicator();
} else if (state is WeatherLoaded) {
return Column(my widget stuff with text widgets to be found);
}
解决方案
天气屏幕使用BlocBuilder
并且在测试时,您没有向此小部件提供任何 BLoC。你应该做的是用 BlocProvider 包装你的MaterialApp
orWeatherScreen
并提供你的WeatherCubit
,例如:
await tester.pumpWidget(
MaterialApp(home:
BlocProvider<WeatherCubit>.value(
value: weatherCubit,
child: WeatherScreen(),
)
),
);
在此之前,您还应该模拟该weatherCubit
值并定义想要的状态。你可以在这里找到一个简单的例子:https ://github.com/felangel/bloc/blob/master/examples/flutter_counter/test/counter/view/counter_view_test.dart
推荐阅读
- css - 如何在样式组件上保持字体大小从父级到子级?
- java - 为什么我们不能将 RSocket 与 Apache Tomcat 一起使用?
- zsh - brew 升级后 PoweLevel9k 崩溃
- python - 在 python try-except 子句的 unittest 中未捕获 AssertError
- python-3.x - 我在我的代码中两次使用相同的模型,如何避免转移权重?
- java - 在不检查存在的情况下解决损坏的符号链接
- html - Safari中的引导列+垂直选项卡受到干扰
- android - 如何计算Android手机从手上掉下来的垂直距离?
- reactjs - 如何在 React.js 中获取 URL 值?
- katalon-studio - 我们可以为katalon studio中的文本字段生成随机的唯一字母吗?