How to use test Firebase functions locally


This specifically relates to running a web project withFirebase. There are two requirements to testing Firebase functions locally before deployment. First you need to run the emulator, and second you need to tell your calling script to use the emulator. And tell it using the correct syntax.

Setup the emulators

Run the following in your project directory (doesn’t owerwrite existing project and choose required services:

firebase init emulators

Start the emulators

If you want to test your entire project locally then run:

firebase emulators:start

But if like me you want to test functions locally (i.e. before you deploy) but want to use production data then run:

firebase emulators:start --only functions,hosting

You should then see feedback confirming your emulators are running and using port 5001.

But they won’t be used by your scripts yet.

Target the emulator

Somewhere in your script that calls the function you should have something along the lines of:

firebase.initializeApp(config);
const fb = firebase.functions();

Below that, you need to add:

fb.useFunctionsEmulator("http://localhost:5001");

I originally tried to shorten this with:

const fb = firebase.functions().useFunctionsEmulator('http://localhost:5000');

But this doesn’t work. Numerous things gave me the console error :

Cannot read property 'httpsCallable' of undefined

But firing up the emulators and targeting them using the final code below worked:

firebase.initializeApp(config);
const fb = firebase.functions();
fb.useFunctionsEmulator("http://localhost:5001");

One response to “How to use test Firebase functions locally”

  1. This fixed it for me, thanks a bunch. Had to hard refresh the site for the changes to take effect. This also only works for firebase version = v8.0 then try using fb.useEmulator(‘localhost’, 5001);

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.