testBloc<B extends BlocBase<State> , State> function
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';
try {
test.expect(states, test.wrapMatcher(expected));
} on test.TestFailure catch (e) {
if (shallowEquality || expected is! List<State>) rethrow;
final diff = _diff(expected: expected, actual: states);
final message = '${e.message}\n$diff';
// ignore: only_throw_errors
throw test.TestFailure(message);
}
}
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()));
}