Why one of my state is not triggered during my test

Issue

I followed Reso code youtube to create a small weather app, but I used the latest bloc library and flutter_bloc 4.0 also.

Base App: https://www.youtube.com/watch?v=hTExlt1nJZI&list=PLB6lc7nQ1n4jCBkrirvVGr5b8rC95VAQ5&index=7

BLoc Test: https://www.youtube.com/watch?v=S6jFBiiP0Mc&list=PLB6lc7nQ1n4jCBkrirvVGr5b8rC95VAQ5&index=8

The first 2 tests are working. For example, the below one does not give me any error:

test(
    'NEWER WAY BUT lONG-WINDED emits [WeatherLoading, WeatherLoaded] when successful',
    () {
  when(mockWeatherRepository.fetchWeather(any))
      .thenAnswer((_) async => weather);

  final bloc = WeatherBloc(mockWeatherRepository);

  bloc.add(GetWeather('London'));

  emitsExactly(bloc, [
    WeatherInitial(),
    WeatherLoading(),
    WeatherLoaded(weather),
  ]);
});

For some reason, that test below does not trigger the WeatherInitial.

blocTest(
  'emits [WeatherLoading, WeatherLoaded] when successful',
  build: () async {
    when(mockWeatherRepository.fetchWeather(any))
        .thenAnswer((_) async => weather);

    return WeatherBloc(mockWeatherRepository);
  },
  act: (bloc) => bloc.add(GetWeather('London')),
  expect: [
    WeatherInitial(),
    WeatherLoading(),
    WeatherLoaded(weather),
  ],
);

The error is:

ERROR: Expected: [
        WeatherInitial:WeatherInitial,
        WeatherLoading:WeatherLoading,
        WeatherLoaded:WeatherLoaded
      ]
Actual: [WeatherLoading:WeatherLoading, WeatherLoaded:WeatherLoaded]
Which: was WeatherLoading:<WeatherLoading> instead of WeatherInitial:<WeatherInitial> at location [0]

Do you have any clue why?

Solution

This behaviour is correct according to the official bloc_test library:

skip is an optional int which can be used to skip any number of states.
The default value is 1 which skips the initialState of the bloc. 
skip can be overridden to include the initialState by setting skip to 0.

So if you want to include your “InitialState” just ,set the “skip” value to 0 :

.
.
.
skip: 0,
expect: [
    WeatherInitial(),
    WeatherLoading(),
    WeatherLoaded(weather),
  ],

Answered By – Juvi

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.