我按照Reso代码youtube创建了一个小型气象应用,但是我也使用了最新的bloc库和flutter_bloc 4.0。
基本应用:https://www.youtube.com/watch?v=hTExlt1nJZI&list=PLB6lc7nQ1n4jCBkrirvVGr5b8rC95VAQ5&index=7
Bloc测试:https://www.youtube.com/watch?v=S6jFBiiP0Mc&list=PLB6lc7nQ1n4jCBkrirvVGr5b8rC95VAQ5&index=8
前两个测试正在运行。例如,以下代码不会给我任何错误:
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),
]);
});
由于某种原因,下面的测试不会触发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),
],
);
错误是:
ERROR: Expected: [
WeatherInitial:WeatherInitial,
WeatherLoading:WeatherLoading,
WeatherLoaded:WeatherLoaded
]
Actual: [WeatherLoading:WeatherLoading, WeatherLoaded:WeatherLoaded]
Which: was WeatherLoading:<WeatherLoading> instead of WeatherInitial:<WeatherInitial> at location [0]
您知道为什么吗?
答案 0 :(得分:2)
根据官方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.
因此,如果您只想包含“ InitialState”,请将“ skip”值设置为0:
.
.
.
skip: 0,
expect: [
WeatherInitial(),
WeatherLoading(),
WeatherLoaded(weather),
],