Cloud Functions — Create, Test, Deploy

Jeremy Lorino
Apr 17, 2018 · 2 min read

How to setup, test, and continuously deploy Firebase Cloud Function v1.0

All code show is available in this git repository. As always feel free to contribute, steal, or do nothing; your choice ;)

So Firebase recently released version 1 of their Cloud Functions. This came with some breaking changes; for those of you that were using Firebase Cloud Functions prior to v1.

It also came with a nice little unit test suite; which totally beats copying and pasting the unit test mocks from the Google Cloud GitHub ;) So lets dive in…

What’s on tap…

Setup

Firebase suggests you develop locally with Node.js v.6.11.5, but since we are going to write everything in TypeScript and let the transpiler do magic we will use Node.js LTS v8.10.0. It works…no worries :)

Clone the git repo:

git clone git@github.com:jeremylorino/firebase-functions-unittest-cd.git

Install Node.js dependencies

npm install

Get some Google Cloud service account credentials

Authenticate with Firebase CLI

Initialize the project directory

Be sure to select your Firebase project from the list

  • Select TypeScript from the language prompt
  • Yes to TSLint
  • NO to all the “Overwrite” questions
  • Yes to install dependencies

Then test it!

npm test

Now what did we just do?

Lets dig into one of the function definitions…

This little snippet is one of the two Firebase Authentication Triggers. When a new Firebase User is created it writes the user’s info to a Firestore document along with a document that will hold the effective permissions for user access control.

Cloud Function triggered by the creation of a Firebase Authentication User

Then we have its associated unit test.

  • Line 3–9: mock Firebase UserRecord
  • Line 11–12: execute the userCreate function with the mock UserRecord
  • Line 17–28: assert the function executed as expected

Now for some continuous deployment

First we will need a Firebase CI token

npm run firebase:citoken
  • Navigate to Build Triggers
  • Connect to git repo
  • Set ‘Build Configuration’ to use the cloudbuild.yaml
  • Set the value of _FIREBASE_TOKEN to what was received from the above command

The End

Google Cloud Platform - Community

A collection of technical articles published or curated by Google Cloud Platform Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.

Jeremy Lorino

Written by

Selling Experiences

Google Cloud Platform - Community

A collection of technical articles published or curated by Google Cloud Platform Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.