jeudi 25 juillet 2019

Testing Flutter BehaviorSubject

This is the service I'm trying to test.

class AccountService {
  AuthLibrary _library;

  BehaviorSubject<User> _user;

  Stream<User> get user => _user.stream.asBroadcastStream();

  AccountService(this._library) : _user = BehaviorSubject() {
    checkUserLogin();
  }

  Future<void> checkUserLogin() async {
    final token = await _library.getToken();
    final tokenLength = token?.length ?? 0;
    return _user.add(tokenLength > 0 ? User(token: token) : null);
  }
}

And this is my test:

class MockAuth extends Mock implements AuthLibrary {}

main() {
  AuthLibrary _auth0;

  setUpAll(() {
    _auth0 = MockAuth();
  });

  test('set user if token is not empty', () async {
    final expected = User(token: "21398712938721");
    when(_auth0.getToken()).thenAnswer((_) async => expected.toString());

    final service = AccountService(_auth0);
    verify(_auth0.getToken()).called(1);
    expect(service.user, emits(expected));
  });
}

I couldn't find on internet how to pass this test. Every example I found out there is using this same patter but for some reason its failing here. So when I run the test I get the following error:

Expected: should emit an event that <Instance of 'User'>
  Actual: <Instance of 'Observable<User>'>
   Which: emitted • Instance of 'User'

Aucun commentaire:

Enregistrer un commentaire