'Bloc test with Flutter, wait for async action

I have this bloc_test in my Flutter code

blocTest<ProjectsBloc, ProjectsState>(
      'emits [ProjectsState.loading(), ProjectsState.succes([])] with empty projects',
      build: () => projectsBloc,
      act: (bloc) => bloc.add(const ProjectsEvent.fetchProjects()),
      wait: const Duration(milliseconds: 2000),
      expect: () => [
        const ProjectsState.loading(),
        const ProjectsState.succes([]),
      ],
    );

If I do not use the wait options the test will fail because the act event will take 1 second. Using wait I can make sure that we wait long enough so the test will be ok. This seems a bit iffy.. so my question is, is there a way to remove the wait option and simply await until the given event is handled?



Solution 1:[1]

I had the same problem, I didn't find a solution via bloc but I was able to modify my code to orient it this way and it allowed my tests to pass.

Before (test doesn't pass)

final product = await _addProductUseCase.retrieveProduct(param);
final photo = await _addProductUseCase.retrieveProductPhoto(param);

After (test passe)

final futures = await Future.wait([
      _addProductUseCase.retrieveProduct(param),
      _addProductUseCase.retrieveProductPhoto(param),
]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1