Flutter: Unit Testing a Cubit issues

1.9k Views Asked by At

I have been trying to set up unit testing for my cubit but bloc test seems to be having issues. Just trying to check the initial state of the values works just fine with regular test but as soon as I try to the same thing with bloc test it spits out fail with the actual being an empty list at [0] and I'm not sure what I'm doing wrong. Nothing on the internet is helpful with this error.

//passes
test('initial state of SettingsCubit', () {
  expect(
      settingsCubit.state,
      SettingsState(
          notificationsEnabled: false,
          gpsEnabled: false,
          celsiusEnabled: false,
          expandNavigation: false,
          breakingNewsNotifications: false,
          trendingNotifications: false,
          liveRemindersNotifications: false,
          sportsNotifications: false));
});

//fails
blocTest(
  'initial state of SettingsCubit',
  build: () => SettingsCubit(),
  expect: () => [
    SettingsState(
      expandNavigation: false,
      gpsEnabled: false,
      celsiusEnabled: false,
      notificationsEnabled: false,
      breakingNewsNotifications: false,
      trendingNotifications: false,
      liveRemindersNotifications: false,
      sportsNotifications: false,
    )
  ],
);

Error:

package:bloc_test/src/bloc_test.dart 193:9   testBloc.<fn>
===== asynchronous gap ===========================
dart:async                                   _asyncThenWrapperHelper
package:bloc_test/src/bloc_test.dart         testBloc.<fn>
dart:async                                   runZonedGuarded
package:bloc_test/src/bloc_test.dart 172:9   testBloc
package:bloc_test/src/bloc_test.dart 140:11  blocTest.<fn>
package:bloc_test/src/bloc_test.dart 139:26  blocTest.<fn>
Expected: [
            SettingsState:SettingsState(expandNavigation: false, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false,breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false)
          ]
  Actual: []
   Which: at location [0] is [] which shorter than expected

SettingsCubit and SettingsState code is at: Flutter BLoC Test failures

1

There are 1 best solutions below

1
On

If you want to test the initial state of your Cubit, you should use the first way (the one that worked for you).

The reason why the second version of the same test (blocTest one) does not work is described in the bloc_test documentation:

[expect] is an optional Function that returns a Matcher which the bloc under test is expected to emit after [act] is executed.

Meaning, you should put all the state changes inside the expect method. But now, you are just creating a BLoC without executing any action after that, your state does not change, hence the actual result - a list of expected state changes - is empty.