Search code examples
flutterunit-testinggoogle-cloud-firestoremocking

Firestore stream test based on fake_cloud_firestore package fails when using converters


I am trying to write a unit test for a Dart function that returns a Firestore stream using fake_cloud_firestore for mocking. It works beautifully when the fakeFirestore instance returns a stream of DocumentSnapshots but fails when those same DocumentSnapshots are converted into actual objects via map().

I have tried lots of combinations of emitLater, stream.take(3), deleting the object to force the closure of the stream and much more. No difference.

The second test always hangs if emitsInOrder([...]] contains more than one element. It might report an error if the first element in the list is not a match but it will still hang if there are additional elements.

I think this indicates that using map() causes the updates that should come in after opening the stream to be ignored. Is there a way to still get this test to work or is fake_cloud_firestore a dead end?

import 'package:equatable/equatable.dart';
import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
import 'package:flutter_test/flutter_test.dart';

import 'document_snapshot_matcher.dart';

// Model class used in the second test
class User extends Equatable {
  final String name;
  final String other;

  const User({required this.name, required this.other});

  @override
  List<Object?> get props => [name, other];

  @override
  bool get stringify => true;

  factory User.fromMap(Map<dynamic, dynamic> map) {
    return User(name: map['name'], other: map['other']);
  }

  Map<String, dynamic> toMap() {
    return {'name': name, 'other': other};
  }

  User copyWith({String? name, String? other}) {
    return User(name: name ?? this.name, other: other ?? this.other);
  }
}

void main() {
  group('Demo Only', () {});

  //This is one of the tests from the fake_cloud_firestore package.
  // https://github.com/atn832/fake_cloud_firestore/blob/master/test/fake_cloud_firestore_test.dart
  // It finishes and passes as expected.
  test('Snapshots returns a Stream of Snapshot', () async {
    final uid = 'abc';
    final instance = FakeFirebaseFirestore();
    expect(
        instance.collection('users').doc(uid).snapshots(),
        emitsInOrder([
          DocumentSnapshotMatcher('abc', null),
          DocumentSnapshotMatcher('abc', {
            'name': 'Bob',
          }),
          DocumentSnapshotMatcher('abc', {
            'name': 'Frank',
          }),
        ]));
    await instance.collection('users').doc(uid).set({
      'name': 'Bob',
    });
    await instance.collection('users').doc(uid).update({
      'name': 'Frank',
    });
  });

  // This is the same test but this time the individual DocumentSnapshots
  // are converted into User objects.
  // This test works as expected when the list passed to emitsInOrder only has
  // one element but it hangs indefinitely if the list has more elements.
  test('Returns a stream of user objects, hangs', () async {
    final uid = 'abc';
    final instance = FakeFirebaseFirestore();

    expect(
        instance
            .collection('users')
            .doc(uid)
            .withConverter<User>(
              fromFirestore: (snapshot, _) => User.fromMap(snapshot.data()!),
              toFirestore: (user, _) => user.toMap(),
            )
            .snapshots()
            .map((snapshot) => snapshot.data()),
        emitsInOrder([
          null,
          User(name: 'Bob', other: 'initial object'),
          User(name: 'Frank', other: 'modified object'),
        ]));

    await instance.collection('users').doc(uid).set({
      'name': 'Bob',
      'other': 'initial object',
    });
    await instance.collection('users').doc(uid).update({
      'name': 'Frank',
      'other': 'modified object',
    });
  });
}

Solution

  • Looks like there is nothing wrong with my test. Instead, the mocking package is not a good replacement for the original.

    https://github.com/atn832/fake_cloud_firestore/pull/295

    This issue gave me a crucial hint. If a stream is opened with a converter, all successive operations will also need a converter, otherwise they are ignored.

    By adding useless converters to my set and update requests, I was able to get my test to finish and pass. Good grief.

    await instance
        .collection('users')
        .doc(uid)
        .withConverter<User>(
          fromFirestore: (snapshot, _) => User.fromMap(snapshot.data()!),
          toFirestore: (user, _) => user.toMap(),
        )
        .set(User(name: 'Bob', other: 'initial object'));
    await instance
        .collection('users')
        .doc(uid)
        .withConverter<User>(
          fromFirestore: (snapshot, _) => User.fromMap(snapshot.data()!),
          toFirestore: (user, _) => user.toMap(),
        )
        .update({
      'name': 'Frank',
      'other': 'modified object',
    });