skip to Main Content
/// A flag that indicates whether the NotificationProvider is being processed.
  bool _isProcess = false;

  set isProcess(bool value) {
    _isProcess = value;
    notifyListeners();
  }

  bool get isProcess => _isProcess;

  NotificationProvider({required this.fetchNotificationUseCase});

  //TODO("Satoshi"): catch exception or error
  /// Fetch notification from api-server.
  Future<void> fetchNotification() async {
    try {
      isProcess = true;
      final res = await fetchNotificationUseCase.fetchNotification();

      notificationList.clear();
      notificationList.addAll(res);

      isProcess = false;
      notifyListeners();
    } catch (e) {
      isProcess = false;
      notifyListeners();
      debugPrint(e.toString());
    }
  }

I want to test isProcess property is changed to true and false. But the only I can test is just isProcess is false after fetchNotification method is completed.
How to test isProcess’s change ?

This is a test code what I wrote

  test('then isProcess is being false', () async {
    await notificationProvider.fetchNotification();

    expect(notificationProvider.isProcess, false);
  });

2

Answers


  1. You can watch value changing using addListener method in ChangeNotifier.

    sample code

    test('isProcess changes true then false', () async {
      expect(notificationProvider.isProcess, false);
      int listenerCounts = 0;
      List<bool> matches = [true, false];
      final listener = () {
        expect(notificationProvider.isProcess, matches[listenerCounts]);
        listenerCounts++;
      }
      notificationProvider.addListener(listener);
      await notificationProvider.fetchNotification();
      notificationProvider.removeListener(listener);
    });
    
    Login or Signup to reply.
  2. fetchNotification synchronously sets isProcess = true before doing asynchronous work. You therefore can synchronously check that notificationProvider.isProcess transitions from false to true and then check that it returns to false after all asynchronous work completes:

      test('then isProcess is being false', () async {
        expect(notificationProvider.isProcess, false);
        var future = notificationProvider.fetchNotification();
        expect(notificationProvider.isProcess, true);
        await future;
        expect(notificationProvider.isProcess, false);
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search