DEV Community

Cover image for Testing a Google Cloud Function locally
Martyn Davies
Martyn Davies

Posted on

Testing a Google Cloud Function locally

Recently I wrote a post about building an app with Google Dialogflow & Algolia. Part of the build for this required the use of a webhook that I decided to build using Google Cloud Functions.

Google has some decent documentation on how to work with GCF in your local environment that includes how to deploy, inspect and debug your functions. It could do with a little more padding and some examples but I'm sure they're getting to it.

When it comes to how you would work with this function locally but allow services outside of your local machine to access it there's no mention of how to do that at all.

Given I've just done this, I thought I'd quickly share what the process was.

Install the GCF Emulator

The Google Cloud Functions Emulator works very much the same way as the main command line interface for GCF does. Once installed you can follow their documentation to get up and running (takes about 5 mins).

Fire up a function

In your development folder you can fire up the emulator using the following commands:

$ functions start //starts the emulator
$ functions deploy myFunctionName --trigger-http //deploys your function as HTTP

Note: A gotcha to watch out for: On my machine (a Macbook Pro) the command functions is already reserved, so I had to use something else. Google provides an alternative command, functions-emulator that you can use instead of functions. You might want to alias this command in your terminal so you don't have to type it out each time.

When a function spins up, you get an output that looks like this:

Google Cloud Functions Emulator Output

Here you can see that the function is up and running on localhost:8010, which is great if everything else you're developing is also running locally but if you have servers elsewhere that need to speak to this endpoint you're going to be stuck.

Luckily, Ngrok still exists.

Open the function to the world

In order to use this local function with servers elsewhere, or as a webhook (which was my use case), you need to expose port 8010 to the world. Ngrok allows you to do this quickly once installed.

In a new terminal tab run:

$ ngrok http 8010

This will open up the port, and give you a URL to use.

Ngrok output

Here we can see that Ngrok has provided public HTTP and HTTPS URLs. We can now use these to access our local Cloud Function by replacing http://localhost:8010 with http://95d039f9.ngrok.io (your URL will differ).

That's it. You're off to the races! Happy serverless development time, folks.

Latest comments (0)