Home > Enterprise >  Dart, bloc_test, expect anystate
Dart, bloc_test, expect anystate

Time:11-23

Say we have a code like this (source: https://resocoder.com/2019/11/29/bloc-test-tutorial-easier-way-to-test-blocs-in-dart-flutter/):

blocTest(
  'emits [WeatherLoading, WeatherLoaded] when successful',
  build: () {
    when(mockWeatherRepository.fetchWeather(any))
        .thenAnswer((_) async => weather);
    return WeatherBloc(mockWeatherRepository);
  },
  act: (bloc) => bloc.add(GetWeather('London')),
  expect: [WeatherInitial(), WeatherLoading(), WeatherLoaded(weather)],
);

Now, I want to create a different test. for this test case, the state that's emitted after the WatherLoading does not matter. It can be WeatherLoaded or any other state. I just want to know if WeatherLoading was emitted. I want to do something like this

blocTest(
  'test i WeatherLoading was emitted',
  build: () {
    when(mockWeatherRepository.fetchWeather(any))
        .thenAnswer((_) async => weather);
    return WeatherBloc(mockWeatherRepository);
  },
  act: (bloc) => bloc.add(GetWeather('London')),
  expect: [WeatherInitial(), WeatherLoading(), AnyState], // Something like this...
);

Are there anyways to achieve this?

CodePudding user response:

You could expect like this instead:

expect: [WeatherInitial(), WeatherLoading(), isA<WeatherState>()],

Where WeatherState is the base class for WeatherInitial and WeatherLoading and so forth.

  • Related