2

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.

Ianmcuki
  • 21
  • 1

1 Answers1

0

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 "import" lines that I added:

  • mock of useCase return with Completer;
  • 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(),
  ],
);
  • even if it was a year ago, providing the BLoC or BLoCTest version used at that time could be helpful in the future. So, thank you to update your solution. – M E S A B O Sep 02 '23 at 02:09