How to override the state of a Riverpod StateNotifier for testing

Viewed 1783

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?

1 Answers

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");
  });
Related