felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.82k stars 3.39k forks source link

Widget Test - Listen to State after Widget was built #3018

Closed karvulf closed 2 years ago

karvulf commented 2 years ago

Description

Hi. I am writing a test where I want to test my BlocListener. The problem is that when using whenListen, the specific state is emitted directly after the widget was built. This happens when I write whenListen first, also I don't see another way to listen to states.

whenListen(bloc, Stream.value(myState));

await tester.pumpWidget(MyWidget()); // myState is directly called after pumping my widget

Desired Solution

My goal is that I want to pump my widget and afterwards, e. g. after a pump, I want to emit a new state to my BlocListener. I am not sure if that's even possible.

await tester.pumpWidget(MyWidget()); // sth is built, so at this point I don't want to listen to a state

whenListen(bloc, Stream.value(myState));

await tester.pump(); // now I want to listen to my state

Maybe I am understanding something totally wrong but is there a way to achieve this?

Thank you for your time and help!

felangel commented 2 years ago

Hi @karvulf 👋 Thanks for opening an issue!

You can use a StreamController in this case like:

final controller = StreamController<MyState>();
whenListen(bloc, controller.stream);
await tester.pumpWidget(...);
controller.add(someState);

Hope that helps 👍

karvulf commented 2 years ago

Works perfect, thank you very much @felangel