How can I test a bloc event using flutter bloc test that has a droppable (or restartable) event?
Event example:
on<SomeEvent>(
_mapSomeEvent,
transformer: droppable(),
);
I tried calling events right after the droppable event inside a flutter bloc test with no success. I also tried using Isolates and stubbing a method inside the droppable event with Future.delayed so it takes longer to process but still didn't get the results I wanted.
Basically, I want some test like this to work:
blocTest<SomeBloc, SomeState>(
'Description',
build: () => SomeBloc(),
act: (bloc) async {
bloc.add(DroppableEvent());
bloc.add(SomeEvent());
},
expect: () => [
StateFromDroppable(),
],
);
With only one state from the droppable event, since the other should be dropped. Instead I get two sates emitted, one from the DroppableEvent and another from SomeEvent.
It was a year ago, but I'll let my solution here:
Supposing that you're calling a async call for an useCase inside your BLoC, the "important" lines that I added:
await Future.delayed(Duration.zero) after adding each one of the events;await Future.delayed(Duration.zero) after completer.complete.final completer = Completer<void>();
blocTest(
"description",
build: () => bloc,
setUp: () {
when(useCase.call).thenAnswer((_) => completer.future);
},
act: (bloc) async {
bloc.add(DroppableEvent());
await Future<void>.delayed(Duration.zero);
bloc.add(SomeEvent());
await Future<void>.delayed(Duration.zero);
completer.complete();
await Future<void>.delayed(Duration.zero);
},
expect: () => [
StateFromDroppable(),
],
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With