How to override the state of a Riverpod StateNotifier for testing
1,062
if you want to override the providers. For instance, when you want to test a specific category. In this case, we can override the ScopedProvider with a value. Then, in the ProviderScope, we can choose which provider to override and choose which value to override
testWidgets('Override the current scope', (tester) async {
await tester.pumpWidget(ProviderScope(
overrides: [
selectedCategory.state.overrideWithValue(Category("Pear", Colors.green))
],
child: HookBuilder(builder: (context) {
return MaterialApp(home: CategoryWidget());
})));
expect((tester.firstWidget(find.byType(Text)) as Text).style.color,
Colors.green);
expect((tester.firstWidget(find.byType(Text)) as Text).data, "Pear");
});
Author by
NirmalCode
I'm a mobile application developer who always loves a challenge
Updated on December 31, 2022Comments
-
NirmalCode over 1 year
I want to override my
StateNotifierProvider
state manually for testing. Overriding providers can be done usingProviderContainer
orProviderScope
. But it only gives the option to override the notifier, not the state.My question is how should I override the state?
-
Admin over 2 yearsPlease provide enough code so others can better understand or reproduce the problem.
-
-
NirmalCode over 2 yearsThanks for answering. Adding a function to every StateNotifierProvider just for testing is a lot of unnecessary work. Also, it may lead to misusing that function. I'm looking for a way without adding anything to existing providers.
-
NirmalCode over 2 yearsThe issue is with
StateNotifierProvider
.overrideWithValue
only allowsNotifiers
as value. Can't override the state. -
Omar Mahmoud over 2 yearsthis article helped me may it help you bartvwezel.nl/flutter/flutter-riverpod-testing-example
-
Matthew Rideout over 2 yearsI am also having this issue, I cannot find a way to override the state of a StateNotifierProvider which returns a class that extends StateNotifier<T>. The only override available is .notifier. I have posted an example of my code and state architecture here: stackoverflow.com/questions/70011054/…