Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Created June 24, 2021 17:08
Show Gist options
  • Save DanielCardonaRojas/2d6bf1f60d8efd821e9e3b92c7bfb5b1 to your computer and use it in GitHub Desktop.
Save DanielCardonaRojas/2d6bf1f60d8efd821e9e3b92c7bfb5b1 to your computer and use it in GitHub Desktop.
Bloc or Cubit test helper, without requiring bloc_test package
import 'package:mocktail/mocktail.dart';
import 'package:meta/meta.dart';
import 'package:bloc/bloc.dart';
import 'dart:async';
import 'package:test/test.dart';
abstract class Callable<T> {
void call([T? arg]) {}
}
class MockCallable<T> extends Mock implements Callable<T> {}
/// Tests a cubit by making assertions on a state field or the state as a whole
///
/// [build] a closure returning the bloc or cubit under test
/// [stateField] the field we want to make assertions on
/// [act] a closure passing the bloc or cubit under test allowing specific events or actions to be triggered
/// [arrange] useful for mocking specific behaviours prior to calling any actions on the bloc or cubit
/// [assertions] create assertions on the emited values as specified by stateField property selector
@isTest
void cubitTest<P, S, B extends BlocBase<S>>(
String description, {
required B Function() build,
required FutureOr Function(B) act,
required P Function(S) stateField,
Function? arrange,
Function(P)? inspect,
required void Function(MockCallable<P> updatesWith) assertions,
}) async {
test(description, () async {
final expectation = MockCallable<P>();
arrange?.call();
final bloc = build();
bloc.stream.listen((S state) {
final focusedProperty = stateField(state);
inspect?.call(focusedProperty);
expectation(focusedProperty);
});
await act(bloc);
await bloc.close();
assertions(expectation);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment