0

I implemented an app using WeatherAPI like in the ResoCoder example. I now want to test if every text widget is showing correct information but I already fail in finding the text widgets (I used this guide https://resocoder.com/2021/01/02/flutter-integration-test-tutorial-firebase-test-lab-codemagic/). I tried it by using find.byKey() (of course set some keys before) and find.byText() but none worked.

My test code:

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);
    });

I always get the error that no those widgets where found:

══╡ 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

And my screen widget:

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);
}

1 Answers1

1

The weather screen uses BlocBuilder and when testing, you are not providing any BLoC to this widget. What you should do, is to wrap your MaterialApp or WeatherScreen with BlocProvider and provide your WeatherCubit, e.g.:

await tester.pumpWidget(
  MaterialApp(home: 
    BlocProvider<WeatherCubit>.value(
      value: weatherCubit,
      child: WeatherScreen(),
    )
  ),
);

Before that, you should also mock the weatherCubit value and define a wanted state. You could find a simple example here: https://github.com/felangel/bloc/blob/master/examples/flutter_counter/test/counter/view/counter_view_test.dart

mkobuolys
  • 4,499
  • 1
  • 11
  • 27