Unit testing Firebase Cloud Functions using the Firestore emulator
Google Firebase simplifies backend development, but its quirks sometimes lead to hours lost searching for solutions. Testing in particular can be challenging, so Google’s recent introduction of the Firebase Local Emulator Suite is encouraging. The Firebase Local Emulator Suite allows for app development and testing to be done locally. This not only prevents unintended changes to production data, but makes unit testing faster and easier. Below are some tips for unit testing Firebase Cloud Functions using the Firestore emulator.
How to get Cloud Functions to use the Firestore emulator
If you’ve written Cloud Functions before, you likely already know that Cloud Functions use the Firebase Admin SDK to read and write data to Firestore, bypassing any applicable Firestore rules. As Firebase does not automatically change the Firestore host when using emulators, Cloud Function operations by default do not use the Firestore emulator.
Forcing the Admin SDK to use a locally emulated instance of Firestore requires modification of the configuration variable FIRESTORE_EMULATOR_HOST
. Assuming the default port is used when configuring the Firestore emulators, the config variable value to use the Firestore emulator will be localhost:8080
. Be sure this configuration variable is changed only when used in test environments with the emulators. One option is to add it to an npm test command in your package.json
file. Below is an…