【问题标题】:Dart / flutter widget test, Text Widgets are not found either by key nor by textDart/flutter 小部件测试,无论是按键还是文本都找不到文本小部件
【发布时间】:2021-07-29 17:24:56
【问题描述】:

我在 ResoCoder 示例中使用 Wea​​therAPI 实现了一个应用程序。我现在想测试是否每个文本小部件都显示了正确的信息,但我已经无法找到文本小部件(我使用了本指南 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);
}

【问题讨论】:

    标签: flutter dart bloc flutter-test cubit


    【解决方案1】:

    天气屏幕使用BlocBuilder,并且在测试时,您没有向此小部件提供任何 BLoC。你应该做的是用 BlocProvider 包装你的 MaterialAppWeatherScreen 并提供你的 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

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2019-06-11
      • 2020-12-11
      • 1970-01-01
      • 2021-02-04
      • 2021-08-13
      • 2023-03-07
      • 2020-02-07
      • 2021-02-22
      相关资源
      最近更新 更多