为什么我的状态之一在我的测试期间没有被触发

Why one of my state is not triggered during my test

我按照 Reso code 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

前 2 个测试有效。例如,下面的一个没有给我任何错误:

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]

你知道为什么吗?

根据官方说法,此行为是正确的 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),
  ],