How to Test GCP Function Locally with Node.js
Table of Contents
- Introduction
- Create Service Account
- Load Service Account
- Run Node.js Locally
- Test The Node.js with BigQuery Access
- How to Debug via Visual Studio Code
- Conclusion
Introduction
This blog shows how to test GCP Cloud Function locally with Node.js. We will set up a service account, load it in our Node.js code, run the function locally, and debug it using Visual Studio Code.
Create Service Account
Create a GCP service account and add the corresponding role. Create a new key and save the file (JSON or P12) locally.
Load Service Account
Next, load the file in the Node.js file.
const options = {
keyFileName: 'location_of_the_file.json',
projectId: 'your_gcp_project_id'
};
const bigquery = new BigQuery(options);
const dataset = bigquery.dataset('my_dataset');
const table = dataset.table('my_table');
Run Node.js Locally
Add the code below to the package.json's script section. When you run this
with the command npm run test, the function will start locally. I have
tested this on macOS with Node version 18; anything below might not work.
"test": "npx functions-framework --target=main [--signature-type=http]",
Test The Node.js with BigQuery Access
Running the command below should start an HTTP server locally. Now you can verify, debug the code, and make sure everything works before running the deploy.
npm run test
How to Debug via Visual Studio Code
Visual Studio Code is a great tool for software development and has improved a
lot since the beginning. One of the features for debugging Node.js in Visual
Studio Code is that you can switch to the JavaScript Debug Terminal and run
npm run test. This will use the built-in debugger attached to the process.
So it is pretty simple to debug Node.js with Visual Studio Code.
Conclusion
Testing GCP Cloud Functions locally before deploying saves time and makes debugging much easier. By setting up a service account and using the functions framework, you can run and test your functions on your local machine. Combined with the Visual Studio Code debugger, you have a smooth local development workflow.