mocktail icon indicating copy to clipboard operation
mocktail copied to clipboard

Issue with mocking where method in Firestore query.

Open Dan-Y-Ko opened this issue 1 year ago • 0 comments

Hello, I am getting the classic "Error type 'Null' is not a subtype of type 'Query<Map<String, dynamic>>'" error but I have stubbed the method and I am still getting this error.

Here's screenshot of the error: https://imgur.com/a/Zqhu2oe

Actual code:

Future<void> _createUser(String? id) async {
    final QuerySnapshot result =
        await _db.collection('Users').where('id', isEqualTo: id).get();

    if (result.docs.isEmpty) {
      await _db.collection("Users").add({
        "id": id,
      });
    }
  }

Test code:

class MockFireStore extends Mock implements FirebaseFirestore {}
class MockCollectionReference extends Mock
    implements CollectionReference<Map<String, dynamic>> {}

class MockQuery extends Mock implements Query<Map<String, dynamic>> {}

class MockQuerySnapshot extends Mock
    implements QuerySnapshot<Map<String, dynamic>> {}

class MockDocumentReference extends Mock
    implements DocumentReference<Map<String, dynamic>> {}

void main() {
   late FirebaseFirestore instance;
   late CollectionReference<Map<String, dynamic>> mockCollectionReference;
   late Query<Map<String, dynamic>> mockQuery;
   late QuerySnapshot<Map<String, dynamic>> mockQuerySnapshot;
   late DocumentReference<Map<String, dynamic>> mockDocumentReference;
   
   setUp(() {
      instance = MockFireStore();
      mockCollectionReference = MockCollectionReference();
      mockQuery = MockQuery();
      mockQuerySnapshot = MockQuerySnapshot();
      mockDocumentReference = MockDocumentReference();
   });

   test('', () async {
      when(() => instance.collection(any()))
          .thenReturn(mockCollectionReference);

      when(() => mockCollectionReference.where(any())).thenReturn(mockQuery);

      when(() => mockQuery.get()).thenAnswer(
        (_) async => mockQuerySnapshot,
      );

      when(() => mockCollectionReference.add(any()))
          .thenAnswer((_) async => mockDocumentReference);
   });
}

I decided to play around with the query and did a direct query on the document instead of querying on the collection with the where and I was able to get the tests passing, so I believe the issue is the where query method, but I'm not sure what the actual issue is.

Dan-Y-Ko avatar Jul 26 '22 04:07 Dan-Y-Ko