Bloc test with Flutter, wait for async action
Asked Answered
R

1

7

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?

Roxie answered 31/10, 2021 at 11:37 Comment(0)
P
0

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),
]);
Pugliese answered 14/4, 2022 at 7:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.