6

I want to test Riverpod StateNotifierProvider. I'm trying to follow a TDD approach for state notifier providers without implementing UI/Widgets.

According to Riverpod documentation on testing, can use ProviderContainer for testing without Widget test. But it doesn't work the way I want.

Scenario : When call function in the provider several state changes happen in order.

Objective : Track all states. Ensure all state changes are in the correct order.

My question :

What's the best way to test these StateNotifierProvider state changes without implementing UI/Widget.

NirmalCode
  • 2,140
  • 1
  • 14
  • 19

1 Answers1

-1

Here's an example about how to use ProviderContainer to track mock state changes from a state notifier provider.

// The provider mock class
class MyProviderMock extends StateNotifier<MyProviderState> with Mock implements MyProvider {
  MyProviderMock() : super(MyProviderInitialState());
}

// A generic Listener class, used to keep track of when a provider notifies its listeners
class Listener<T> extends Mock {
  void call(T? previous, T next);
}

void main() {
  final providerMock = MyProviderMock();
  
  test('states are emitted in sequence', () {
    final container = ProviderContainer(
        overrides: [
          myProviderReference.overrideWith((ref) => providerMock),
        ],
      );
    final listener = ListenerMock<MyProviderState>();
    container.listen<MyProviderState>(myProviderReference, listener, fireImmediately: true);

      verifyInOrder(
        [
          () => listener(null, MyProviderLoadingState()),
          () => listener(MyProviderLoadingState(), MyProviderLoadedState()),
          () => listener(MyProviderLoadedState(), AnyOtherState()),
        ],
      );

      verifyNoMoreInteractions(listener);
  }

}

Full ref of the example above: https://codewithandrea.com/articles/unit-test-async-notifier-riverpod/

GGirotto
  • 848
  • 2
  • 10
  • 31