testBloc<B extends BlocBase<State>, State> function

  1. @visibleForTesting
Future<void> testBloc<B extends BlocBase<State>, State>({
  1. FutureOr<void> setUp()?,
  2. required B build(),
  3. State seed()?,
  4. dynamic act(
    1. B bloc
    )?,
  5. Duration? wait,
  6. int skip = 0,
  7. dynamic expect()?,
  8. dynamic verify(
    1. B bloc
    )?,
  9. dynamic errors()?,
  10. FutureOr<void> tearDown()?,
})

Internal blocTest runner which is only visible for testing. This should never be used directly -- please use blocTest instead.

Implementation

@visibleForTesting
Future<void> testBloc<B extends BlocBase<State>, State>({
  FutureOr<void> Function()? setUp,
  required B Function() build,
  State Function()? seed,
  Function(B bloc)? act,
  Duration? wait,
  int skip = 0,
  dynamic Function()? expect,
  Function(B bloc)? verify,
  dynamic Function()? errors,
  FutureOr<void> Function()? tearDown,
}) async {
  final unhandledErrors = <Object>[];
  var shallowEquality = false;
  await runZonedGuarded(
    () async {
      await setUp?.call();
      final states = <State>[];
      final bloc = build();
      // ignore: invalid_use_of_visible_for_testing_member, invalid_use_of_protected_member
      if (seed != null) bloc.emit(seed());
      final subscription = bloc.stream.skip(skip).listen(states.add);
      try {
        await act?.call(bloc);
      } catch (error) {
        unhandledErrors.add(
          error is BlocUnhandledErrorException ? error.error : error,
        );
      }
      if (wait != null) await Future<void>.delayed(wait);
      await Future<void>.delayed(Duration.zero);
      await bloc.close();
      if (expect != null) {
        final dynamic expected = expect();
        shallowEquality = '$states' == '$expected';
        test.expect(states, test.wrapMatcher(expected));
      }
      await subscription.cancel();
      await verify?.call(bloc);
      await tearDown?.call();
    },
    (Object error, _) {
      if (error is BlocUnhandledErrorException) {
        unhandledErrors.add(error.error);
      } else if (shallowEquality && error is test.TestFailure) {
        // ignore: only_throw_errors
        throw test.TestFailure(
          '''${error.message}
WARNING: Please ensure state instances extend Equatable, override == and hashCode, or implement Comparable.
Alternatively, consider using Matchers in the expect of the blocTest rather than concrete state instances.\n''',
        );
      } else {
        // ignore: only_throw_errors
        throw error;
      }
    },
  );
  if (errors != null) test.expect(unhandledErrors, test.wrapMatcher(errors()));
}