how to test Cloud Functions for Firebase locally on pc

16,406

Solution 1

firebaser here

Deployment of your Functions indeed takes more time than what I'm normally willing to wait for. We're working hard to improve that and (as Brendan said) are working on a local emulator.

But for the moment, I mostly write my actual business logic into a separate Node script first. That way I can test it from a local command prompt with node speech.js. Once I'm satisfied that the function works, I either copy/paste it into my actual Functions file or (better) import the speech module into my functions file and invoke it from there.

One abbreviated example that I quickly dug up is when I was wiring up text extraction using the Cloud Vision API. I have a file called ocr.js that contains:

var fetch = require('node-fetch');

function extract_text(url, gcloud_authorization) {
  console.log('extract_text from image '+url+' with authorization '+gcloud_authorization);

  return fetch(url).then(function(res) {
    return res.buffer();
  }).then(function(buffer) {
    return fetch('https://vision.googleapis.com/v1/images:annotate?key='+gcloud_authorization, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        "requests":[
          {
            "image":{
              "content": buffer.toString('base64')
            },
            "features":[
              {
                "type":"TEXT_DETECTION",
                "maxResults":1
              }
            ]
          }
        ]
      })
    });
  }).then(function(res) {
    var json = res.json();
    if (res.status >= 200 && res.status < 300) {
      return json;
    } else {
      return json.then(Promise.reject.bind(Promise));
    }
  }).then(function(json) {
    if (json.responses && json.responses.length && json.responses[0].error) {
      return Promise.reject(json.responses[0].error);
    }
    return json.responses[0].textAnnotations[0].description;
  });
}

if (process.argv.length > 2) {
  // by passing the image URL and gcloud access token, you can test this module
  process.argv.forEach(a => console.log(a));
  extract_text(
    process.argv[2], // image URL
    process.argv[3]  // gcloud access token or API key
  ).then(function(description) {
    console.log(description);
  }).catch(function(error) {
    console.error(error);
  });
}

exports.extract_text = extract_text;

And then in my Functions index.js, I have:

var functions = require('firebase-functions');
var fetch = require('node-fetch');
var ocr = require('./ocr.js');

exports.ocr = functions.database().path('/messages/{room}/{id}').onWrite(function(event) {
  console.log('OCR triggered for /messages/'+event.params.room+'/'+event.params.id);

  if (!event.data || !event.data.exists()) return;
  if (event.data.ocr) return;
  if (event.data.val().text.indexOf("https://firebasestorage.googleapis.com/") !== 0) return; // only OCR images

  console.log(JSON.stringify(functions.env));

  return ocr.extract_text(event.data.val().text, functions.env.googlecloud.apikey).then(function(text) {
    return event.data.adminRef.update({ ocr: text });
  });
});

So as you can see this last file is really just about wiring up the "worker method" ocr.extract_text to the database location.

Note this is a project from a while ago, so some of the syntax (mostly the functions.env part) might have changed a bit.

Solution 2

firebaser here

To debug your Cloud Functions for Firebase locally, there is an emulator. See the documentation for more info.

Solution 3

run and debug/inspect functions locally

prerequisites (google-cloud functions and firebase-specific):

npm install -g @google-cloud/functions-emulator
npm install --save firebase-functions
npm install -g firebase-tools

To run and inspect/debug: first run functions locally, then inspect each function, and finally run each specific function to debug+inspect it. Use functions start as an alternative to firebase serve and note the documentation for each tool is available (and useful).

To run and debug the specific function myFn as-expected (eg in Nodejs via chrome://inspect and note this works using Nodejs v10 though not officially supported):

firebase serve --only functions
functions inspect myFn
functions call myFn # or call from browser

additional documentation:

https://firebase.google.com/docs/functions/local-emulator https://cloud.google.com/functions/docs/emulator#debug-emulator https://github.com/GoogleCloudPlatform/cloud-functions-emulator/wiki

Solution 4

>> Is there any way to test Cloud Functions for Firebase locally?

You can use the following command to start a firebase shell (execute in your functions directory):

npm run build && firebase functions:shell

You can invoke your functions in the shell like so:

helloWorld()

Refer this link for more information.

Solution 5

Answered here: https://github.com/firebase/firebase-functions/issues/4#issuecomment-286515989

Google Cloud Functions also open-sourced a local emulator, and we are working to build a tighter integration with Cloud Functions for Firebase. In the meanwhile, you can check it at here: https://github.com/GoogleCloudPlatform/cloud-functions-emulator/

The emulator does allow you to run functions locally. Here's the documentation that explains how to use it: https://cloud.google.com/functions/docs/emulator

Share:
16,406
Inzamam Malik
Author by

Inzamam Malik

I'm an Artificial Intelligence Chatbot and VUI developer (Voice User Interface developer) have capability of making Intelligent Chatbot with highly scaleable containerized backend with cutting edge technologies Along with web and mobile apps I am specialized in making conversational Interfaces and business chatbots using the highly adopted platform Dialogflow(api.ai) I'm able to provide you a complete solution for: Google Home / Google assistant Alexa / amazon echo Facebook Messenger platform Customized Chatbot to integrate in Android, iOS and Web Apps

Updated on June 08, 2022

Comments

  • Inzamam Malik
    Inzamam Malik almost 2 years

    Today Firebase released its brand new product Cloud Functions for Firebase and I just created a hello world function and deploy it on my existing firebase project.

    It looks like it bundles all dependencies and upload it to firebase just like aws lambda function does. But it takes too much time to be done even on minor changes in code and also need a good connectivity of internet . If you are offline for some reason, you are just in dark what code you are writing until you have a way to execute and test that functions offline on your local machine.

    Is there any way to test Cloud Functions for Firebase locally?

  • Inzamam Malik
    Inzamam Malik about 7 years
    can you please share any example in action, or atleast refer to any repo containing hello world program of what you are describing in your answer
  • Brian Lenoski
    Brian Lenoski almost 7 years
    Alpha version firebase emulator for https functions available: firebase.google.com/docs/functions/local-emulator
  • Han Whiteking
    Han Whiteking over 6 years
    can do singlestepping? Allow checking value of variables?
  • Let Me Tink About It
    Let Me Tink About It over 6 years
    How does the testing work in practice? You mentioned you run node speech.js at the command line. But this does not test the operational logic of your program correct? It only tests the "setup" (i.e., syntax, dependencies, etc.) I'm guessing? If this is correct, is there any way to test the operational logic locally?
  • Frank van Puffelen
    Frank van Puffelen over 6 years
    I pass in the values that the GCP needs from the command line. So it tests my script and its interactions with the external API. It does not test the actual flow if data into Cloud Functions.
  • Tom
    Tom over 5 years
    I find it easier to do your log of process.pid at the top of index.js. It gets evaluated for each new process and this will happen as soon as you run 'firebase serve' - no need to do a request to get it.
  • adelphus
    adelphus over 5 years
    @Tom except that doesn't seem to work. As I mentioned, a new process is launched when the first function is called. You can verify this by seeing the process ID logged at the top of index.js is different from the process ID returned from the /processid function call.
  • Tom
    Tom over 5 years
    Oh, that's odd. I'm pretty sure it was working for me. I'll recheck next time I'm working on that - maybe its behavior is inconsistent in this regard.
  • quickdraw mcgraw
    quickdraw mcgraw about 5 years
    Thanks @adelphus this is exactly what I have been looking for, works a treat.
  • fischermatte
    fischermatte over 4 years
    @BrianLenoski seems the debugging option is gone? The link you provided shows how to run locally, but not how to debug.
  • Elia Weiss
    Elia Weiss over 4 years
    I get Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com
  • Elia Weiss
    Elia Weiss over 4 years
    How do I attach to a process?