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");
  });
Share:
1,062
NirmalCode
Author by

NirmalCode

I'm a mobile application developer who always loves a challenge

Updated on December 31, 2022

Comments

  • NirmalCode
    NirmalCode over 1 year

    I want to override my StateNotifierProvider state manually for testing. Overriding providers can be done using ProviderContainer or ProviderScope. But it only gives the option to override the notifier, not the state.

    My question is how should I override the state?

    • Admin
      Admin over 2 years
      Please provide enough code so others can better understand or reproduce the problem.
  • NirmalCode
    NirmalCode over 2 years
    Thanks 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
    NirmalCode over 2 years
    The issue is with StateNotifierProvider. overrideWithValue only allows Notifiers as value. Can't override the state.
  • Omar Mahmoud
    Omar Mahmoud over 2 years
    this article helped me may it help you bartvwezel.nl/flutter/flutter-riverpod-testing-example
  • Matthew Rideout
    Matthew Rideout over 2 years
    I 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/…