Firebase Cloud Functions Local Test

Firebase Logo

This article is about testing Firebase Cloud Functions on your local machine. Setting up the local testing environment is as easy as deploying Cloud Functions.

Prerequisite

Node.js

Firebase SDK

Install Firebase SDK if you haven't.

$ npm install -g firebase-tools

Once you initialize your project, install firebase-functions and firebase-admin in the functions directory.

$ npm install -s firebase-functions@latest firebase-admin

Setting an alias to the project would save you from typing the project ID every time.

$ firebase use --add
? Which project do you want to add?
> [Select Your Project ID]
? What alias do you want to use for this project? (e.g. staging)
> Set The Alias

Testing Functions

They provide two interfaces for test execution: URL and Interactive Shell

URL

Basically, all you have to do is to replace deploy with serve. You will see a URL starts with localhost on success.

# For functions only
$ firebase serve --only functions
# If you are using the Firebase Hosting
$ firebase serve

Interactive Shell

This is more intuitive and I would personally recommend this way.

$ firebase functions:shell

Call the exported function name directly to execute them. For example, if there is a function exported as helloWorld, you can call it as below:

firebase > helloWorld()

If you use http methods to trigger different process, call as below. You can also pass a sub-path in the argument.

firebase> helloHttps()
firebase> helloHttps.get()
firebase> helloHttps.post('path')

Pass data if you would like to execute a function that gets triggered by database events. Use a key-value object for Firestore.

# Realtime
Databasefirebase> myRealtimeDBFunction('data')
# Upsert
firebase> myRealtimeDBFunction({before: 'old_data', after: 'new_data' })
# Firestore
firebase> myFirestoreFunction({foo: 'data'})

Real Database Connection

Even though the functions locally exist and are executed, they refer to real databases. So it is technically not absolutely local. You can unit test purely offline functions. However, note that it would require a lot of stubs and can be a lot of work. Read the official document to learn how to set it up.

References

COPYRIGHT © 2023 Kohei Ando