When I run my app normally, I execute cubit.getWeather('London') and the weatherLoading state emits, then weatherLoaded state emits CORRECTLY.
However when I run test for the cubit to test cubit.getWeather('London'), the weatherLoading state isn't emitted - it jumps straight to weatherLoaded state.
Why is this happening?
State:
@freezed
abstract class WeatherState with _$WeatherState {
factory WeatherState.weatherInitial() = WeatherInitial;
factory WeatherState.weatherLoading() = WeatherLoading;
factory WeatherState.weatherLoaded(Weather weather) = WeatherLoaded;
factory WeatherState.weatherError(String message) = WeatherError;
}
Cubit:
class WeatherCubit extends Cubit<WeatherState> {
final WeatherRepository _weatherRepository;
static Weather weather;
WeatherCubit(this._weatherRepository) : super(WeatherState.weatherInitial());
Future<void> getWeather(String cityName) async {
emit(WeatherState.weatherLoading());
try {
final weather = await _weatherRepository.fetchWeather(cityName);
emit(WeatherState.weatherLoaded(weather));
} on NetworkException {
emit(WeatherState.weatherError("Network error"));
}
}
}
My weather repository class has 'Future<Weather> fetchWeather(String cityname){...}' method.
And finally, my test:
class MockWeatherRepository extends Mock implements WeatherRepository {}
void main() {
MockWeatherRepository mockWeatherRepository;
WeatherCubit cubit;
final weather = Weather(cityName: 'London', temperatureCelsius: 7);
setUp(() {
mockWeatherRepository = MockWeatherRepository();
when(mockWeatherRepository.fetchWeather(any))
.thenAnswer((_) async => weather);
cubit = WeatherCubit(mockWeatherRepository);
});
test(
'emits [WeatherLoading, WeatherLoaded] when successful',
() async {
cubit.getWeather('London');
await expectLater(
cubit,
emitsInOrder([ //Fails
WeatherState.weatherLoading(),
WeatherState.weatherLoaded(weather),
]),
);
},
);
}