Closed georgek1991 closed 3 years ago
Hi @georgek1991 👋 Thanks for opening an issue!
I believe the problem is you're pumping a widget which already creates and provides the bloc internally. Your widget tree ends up looking something like:
- BlocProvider<MockShortListBloc>
- MaterialApp
- ShortListPage
- BlocProvider<ShortListBloc>
The nearest provided bloc will always be used so you should decompose your ShortListPage
into a page and view:
class ShortListPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => ShortListBloc(),
child: ShortListView(),
);
}
}
class ShortListView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<ShortListBloc, ShortListState>(...);
}
}
This allows you to decouple the widget providing the bloc from the widget which consumes the bloc and makes it easy to inject a mock instance. In your tests you could then pump the ShortListView
wrapped by a BlocProvider with a mock instance and it should work:
when(() => shortListBloc.state).thenReturn(...);
await tester.pumpWidget(
BlocProvider.value(
value: shortListBloc,
child: ShortListView(),
),
);
Hope that helps 👍
@georgek1991 were you able to resolve the issue? If so can we close this issue? Thanks 🙏
Yes @felangel
Thanks for the help
Hi @felangel,
I am trying to test my ShortListPage page. I have added bloc_test and mocktail to the project dependencies. This is my code
ShortListPage.dart
ShortListPage_test.dart
main.dart
The issue I am facing is that I am not able to mock the mockShortListBloc.state. Even though I am giving it inside the 'when' statement it does not change the state in my ShortListPage.
I also tried
await tester.pumpAndSettle();
but as the state is not changing there is an infinite loading which causing timeout.I am not sure where I am doing wrong.
Can you please help?