mobxjs / mobx.dart

MobX for the Dart language. Hassle-free, reactive state-management for your Dart and Flutter apps.
https://mobx.netlify.app
MIT License
2.4k stars 310 forks source link

mobx_test package? #121

Closed brianegan closed 5 years ago

brianegan commented 5 years ago

Just a passing thought, but I was wondering if mobx might be amenable to a mobx_test package that provides custom matchers for observables? I'm taking inspiration from Stream Matchers, here: https://pub.dartlang.org/packages/test#stream-matchers

For example, say you want to verify that an observable emits two states in response to an action, it might be coo to have something like (pseudocode warning, might not be 100% right, but to get the idea across!):

test('My action updates the observable in a specific way', () {
  final myObservable = Observable<int>(0);
  void myAction() async {
    runInAction(() {
      myObservable.value = 1;
    });

   final result = await fetchInt(); // mock this to return "2"

   runInAction(() {
    myObservable.value = result;
   });
  }

  scheduleMicrotask(() { 
    myAction();
  });

  // The `notifiesInOrder` would be a custom test matcher exported from the mobx_test package
  expect(myObservable.value, notifiesInOrder([1, 2]));
});

This can be really handy when it comes to testing logic, especially if you want the Observable to be in an expected state in response to an API or async call. An example of test where I use this for the bloc pattern and really like the approach:

https://github.com/brianegan/github_search_angular_flutter/blob/master/github_search_common/test/ui/search_bloc_test.dart

Potential matchers, using notifies in place of emit, but naming is just for demonstration and open to feedback:

Update, I think this could help your own tests as well! E.g. this kinda stuff here:

  final values = <int>[];
      autorun((_) {
        values.add(counter.value);
      });

We used to do this EXACT same thing in RxDart before StreamMatchers were available, and they really clean up the testing code.

pavanpodila commented 5 years ago

That's a good suggestion @brianegan. I am very open to having a matcher package, specifically for mobx-focused tests.

If you are writing logic tests for MobX, you can rely on when() or asyncWhen() as well.

pavanpodila commented 5 years ago

Closing this for now.