For testing a Swift application that pulls from Firestore, how do I mock QuerySnapshot?

by Matt Ruiz   Last Updated September 12, 2019 02:26 AM

I have a swift function with the signature func getItem(querySnapshot: QuerySnapshot) and I don't know how to mock querySnapshot.

QuerySnapshot is a .h file which I'm not too familiar with. From reading, it seems like it's just a public-facing interface which is used instead of the actual implementation (please correct if wrong). I tried subclassing from this and using that but I'm not even sure where to add test data to it.

func getItem(querySnapshot: QuerySnapshot) {
    for document in querySnapshot.documents {
        let cost = document.get("cost");

I'm in the process of refactoring to where I am less reliant on the QuerySnapshot and convert to an Item prior to the call to this method; which would make my life a lot easier.

Answers 1

When dealing with testing and Firebase, there doesn't seem to be a lot of great testing infrastructure, especially for unit tests. The best thing to do is to create data objects that abstract away Firestore, use those objects throughout your code (instead of relying on Firestore), and test with that.

One thing that's been useful is CodableFirebase, which will let you decode and encode your snapshot into a Codable object. For example, if you create the simple data object

class MyDocument: Codable {
  var name: String
  var age: Int

You can then decode/encode your data using FirestoreEncoder().encode or FirestoreDecoder.decode()

September 12, 2019 02:24 AM

Related Questions

firestore cloud messaging iOS Swift

Updated January 24, 2019 15:26 PM

Firebase Cloud Firestore - Initializing a Collection

Updated October 06, 2018 02:26 AM

Firestore document creation fails without an error

Updated March 06, 2019 10:26 AM