Testing Google Cloud Functions: Unit, Integration & End-to-End

Testing Google Cloud Functions: Unit, Integration & End-to-End

Google Cloud Functions let you deploy individual pieces of business logic without managing servers. But that flexibility comes with a testing challenge: how do you verify a function that runs in Google's managed environment before you ship it? Testing GCF properly requires understanding the local emulation tools available, structuring your code for testability, and building an integration test strategy that doesn't require deploying to GCP on every iteration.

This guide covers everything from fast unit tests to full end-to-end verification, for both HTTP-triggered and background (event-driven) functions.

Understanding the Two Types of Cloud Functions

Google Cloud Functions come in two flavors, and each requires a slightly different testing approach:

HTTP functions are triggered by HTTP requests. They receive a standard request and response object, similar to Express.js middleware. Testing these is relatively straightforward since you can make HTTP calls against a local server.

Background functions (also called event-driven functions) are triggered by Google Cloud events: Pub/Sub messages, Cloud Storage changes, Firestore writes, and so on. They receive an event object and a callback (or return a Promise in newer runtimes). Testing these requires generating synthetic event payloads.

Setting Up the Functions Framework Locally

The Functions Framework for Node.js is Google's official local development server for Cloud Functions. It runs your function in an environment that closely matches the production runtime.

npm install --save-dev @google-cloud/functions-framework

For an HTTP function:

// src/users.js
const { Firestore } = require('@google-cloud/firestore');

const db = new Firestore();

exports.getUser = async (req, res) => {
    const userId = req.params.userId || req.query.userId;

    if (!userId) {
        return res.status(400).json({ error: 'userId is required' });
    }

    try {
        const doc = await db.collection('users').doc(userId).get();

        if (!doc.exists) {
            return res.status(404).json({ error: 'User not found' });
        }

        res.json({ id: doc.id, ...doc.data() });
    } catch (err) {
        console.error('Firestore error:', err);
        res.status(500).json({ error: 'Internal server error' });
    }
};

Start it locally:

npx functions-framework --target=getUser --port=8080
curl http://localhost:8080?userId=user-123

For a Pub/Sub background function:

// src/processOrder.js
exports.processOrder = async (message, context) => {
    const data = Buffer.from(message.data, 'base64').toString('utf8');
    const order = JSON.parse(data);

    console.log(`Processing order ${order.id} for ${order.userId}`);

    // Business logic here
    await fulfillOrder(order);
};

Start it in CloudEvent mode:

npx functions-framework --target=processOrder --signature-type=cloudevent

Send a test event:

curl -X POST http://localhost:8080 \
  -H "Content-Type: application/json" \
  -H "ce-id: test-event-1" \
  -H "ce-type: google.cloud.pubsub.topic.v1.messagePublished" \
  -H "ce-source: //pubsub.googleapis.com/projects/my-project/topics/orders" \
  -H "ce-specversion: 1.0" \
  -d '{
    "message": {
      "data": "eyJpZCI6Im9yZGVyLTEyMyIsInVzZXJJZCI6InVzZXItNDU2In0=",
      "messageId": "test-msg-1",
      "publishTime": "2024-01-01T00:00:00Z"
    }
  }'

The base64 data decodes to {"id":"order-123","userId":"user-456"}.

Unit Testing with Jest

Unit tests should run without any network calls or Google Cloud dependencies. The key is structuring your code to separate business logic from GCP SDK calls.

// src/users.js — dependency-injectable version
const { Firestore } = require('@google-cloud/firestore');

let _db;

function getDb() {
    if (!_db) {
        _db = new Firestore();
    }
    return _db;
}

// Export for testing
exports._setDb = (db) => { _db = db; };

exports.getUser = async (req, res) => {
    const userId = req.params.userId || req.query.userId;

    if (!userId) {
        return res.status(400).json({ error: 'userId is required' });
    }

    try {
        const db = getDb();
        const doc = await db.collection('users').doc(userId).get();

        if (!doc.exists) {
            return res.status(404).json({ error: 'User not found' });
        }

        res.json({ id: doc.id, ...doc.data() });
    } catch (err) {
        res.status(500).json({ error: 'Internal server error' });
    }
};

Now write unit tests with Jest:

// src/users.test.js
const { getUser, _setDb } = require('./users');

// Helper to build mock request/response objects
function buildReq(overrides = {}) {
    return {
        params: {},
        query: {},
        body: {},
        ...overrides
    };
}

function buildRes() {
    const res = {
        statusCode: 200,
        data: null,
        status(code) {
            this.statusCode = code;
            return this;
        },
        json(data) {
            this.data = data;
            return this;
        }
    };
    return res;
}

// Mock Firestore
function buildMockDb(docData) {
    return {
        collection: () => ({
            doc: () => ({
                get: async () => ({
                    exists: docData !== null,
                    id: 'user-123',
                    data: () => docData
                })
            })
        })
    };
}

beforeEach(() => {
    jest.clearAllMocks();
});

test('returns 400 when userId is missing', async () => {
    const req = buildReq();
    const res = buildRes();

    await getUser(req, res);

    expect(res.statusCode).toBe(400);
    expect(res.data.error).toBe('userId is required');
});

test('returns 200 with user data when found', async () => {
    _setDb(buildMockDb({ name: 'Alice', email: 'alice@example.com' }));

    const req = buildReq({ query: { userId: 'user-123' } });
    const res = buildRes();

    await getUser(req, res);

    expect(res.statusCode).toBe(200);
    expect(res.data.name).toBe('Alice');
    expect(res.data.id).toBe('user-123');
});

test('returns 404 when user does not exist', async () => {
    _setDb(buildMockDb(null));

    const req = buildReq({ query: { userId: 'ghost' } });
    const res = buildRes();

    await getUser(req, res);

    expect(res.statusCode).toBe(404);
    expect(res.data.error).toBe('User not found');
});

For Python functions using pytest:

# main.py
import json
from google.cloud import firestore

_db = None

def get_db():
    global _db
    if _db is None:
        _db = firestore.Client()
    return _db

def set_db(db):
    global _db
    _db = db

def get_user(request):
    user_id = request.args.get('userId')

    if not user_id:
        return json.dumps({'error': 'userId is required'}), 400

    db = get_db()
    doc = db.collection('users').document(user_id).get()

    if not doc.exists:
        return json.dumps({'error': 'User not found'}), 404

    return json.dumps({'id': doc.id, **doc.to_dict()}), 200
# test_main.py
import json
from unittest.mock import MagicMock
import pytest
import main

class MockRequest:
    def __init__(self, args=None):
        self.args = args or {}

def make_mock_doc(exists, data=None):
    doc = MagicMock()
    doc.exists = exists
    doc.id = 'user-123'
    doc.to_dict.return_value = data or {}
    return doc

def make_mock_db(doc):
    db = MagicMock()
    db.collection.return_value.document.return_value.get.return_value = doc
    return db

def test_returns_400_when_user_id_missing():
    request = MockRequest()
    body, status = main.get_user(request)
    assert status == 400
    assert json.loads(body)['error'] == 'userId is required'

def test_returns_user_when_found():
    mock_doc = make_mock_doc(True, {'name': 'Alice', 'email': 'alice@example.com'})
    main.set_db(make_mock_db(mock_doc))

    request = MockRequest({'userId': 'user-123'})
    body, status = main.get_user(request)

    assert status == 200
    data = json.loads(body)
    assert data['name'] == 'Alice'

def test_returns_404_when_not_found():
    mock_doc = make_mock_doc(False)
    main.set_db(make_mock_db(mock_doc))

    request = MockRequest({'userId': 'ghost'})
    body, status = main.get_user(request)

    assert status == 404

Integration Testing with Firebase Emulators

The Firebase Emulator Suite is the most complete local emulation option for Google Cloud. It supports Firestore, Auth, Pub/Sub, Cloud Functions, Storage, and more — all running locally with no GCP account required.

Install the Firebase CLI:

npm install -g firebase-tools
firebase login
firebase init emulators

Configure firebase.json:

{
  "emulators": {
    "functions": {
      "port": 5001
    },
    "firestore": {
      "port": 8080
    },
    "pubsub": {
      "port": 8085
    },
    "ui": {
      "enabled": true,
      "port": 4000
    }
  }
}

Start the emulators:

firebase emulators:start

Now write integration tests that run against the emulator:

// integration/users.integration.test.js
const { initializeApp } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');
const axios = require('axios');

// Point Firebase Admin SDK at the emulator
process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080';
process.env.FIREBASE_STORAGE_EMULATOR_HOST = 'localhost:9199';

const app = initializeApp({ projectId: 'test-project' });
const db = getFirestore(app);

const FUNCTIONS_URL = 'http://localhost:5001/test-project/us-central1';

beforeAll(async () => {
    // Seed test data in the emulated Firestore
    await db.collection('users').doc('user-123').set({
        name: 'Alice',
        email: 'alice@example.com',
        createdAt: new Date()
    });
});

afterAll(async () => {
    // Clear emulator data between test runs
    await axios.delete(
        'http://localhost:8080/emulator/v1/projects/test-project/databases/(default)/documents'
    );
});

test('GET /getUser returns user data', async () => {
    const response = await axios.get(`${FUNCTIONS_URL}/getUser?userId=user-123`);
    expect(response.status).toBe(200);
    expect(response.data.name).toBe('Alice');
});

test('GET /getUser returns 404 for missing user', async () => {
    try {
        await axios.get(`${FUNCTIONS_URL}/getUser?userId=nonexistent`);
        fail('Expected 404');
    } catch (err) {
        expect(err.response.status).toBe(404);
    }
});

Testing Pub/Sub Triggered Functions

For event-driven functions, use the @google-cloud/pubsub client pointed at the emulator:

// integration/processOrder.integration.test.js
const { PubSub } = require('@google-cloud/pubsub');

process.env.PUBSUB_EMULATOR_HOST = 'localhost:8085';

const pubsub = new PubSub({ projectId: 'test-project' });

beforeAll(async () => {
    // Ensure the topic exists
    try {
        await pubsub.createTopic('orders');
    } catch (err) {
        // Topic may already exist
    }
});

test('processOrder function handles a valid order', async () => {
    const order = { id: 'order-999', userId: 'user-123', amount: 49.99 };
    const dataBuffer = Buffer.from(JSON.stringify(order));

    const messageId = await pubsub.topic('orders').publish(dataBuffer);
    expect(messageId).toBeDefined();

    // Give the function time to process
    await new Promise(resolve => setTimeout(resolve, 2000));

    // Assert side effects — e.g., check Firestore for a fulfillment record
    // const fulfillment = await db.collection('fulfillments').doc('order-999').get();
    // expect(fulfillment.exists).toBe(true);
});

Testing Firestore-Triggered Functions

Cloud Functions that fire on Firestore changes are the trickiest to test because the trigger comes from a database write, not an HTTP call.

With the emulator, you can trigger these functions by writing to the emulated Firestore:

// integration/onUserCreate.integration.test.js
test('onUserCreate sends welcome email', async () => {
    // Writing to emulated Firestore will trigger the function
    await db.collection('users').doc('new-user').set({
        name: 'Bob',
        email: 'bob@example.com'
    });

    // Wait for function execution
    await new Promise(resolve => setTimeout(resolve, 1500));

    // Assert side effect — maybe a record in an 'emails' collection
    const emailDoc = await db.collection('emails').doc('new-user').get();
    expect(emailDoc.exists).toBe(true);
    expect(emailDoc.data().to).toBe('bob@example.com');
});

For unit testing Firestore-triggered handlers directly, use the firebase-functions-test library:

const functionsTest = require('firebase-functions-test')(
    { projectId: 'test-project' },
    './service-account.json'  // or use emulator
);

const { onUserCreate } = require('../src/onUserCreate');

test('sends welcome email on user create', async () => {
    const snap = functionsTest.firestore.makeDocumentSnapshot(
        { name: 'Bob', email: 'bob@example.com' },
        'users/new-user'
    );

    const wrapped = functionsTest.wrap(onUserCreate);
    await wrapped(snap);

    // Assert your side effects
});

End-to-End Testing in a Staging Environment

After unit and integration tests pass locally, a final layer of E2E tests against a dedicated staging GCP project gives you confidence before production deployment.

Keep E2E tests minimal — just the critical paths. Use real GCP services in a non-production project:

// e2e/api.e2e.test.js
const axios = require('axios');

const STAGING_URL = process.env.STAGING_FUNCTIONS_URL;

test('user creation and retrieval flow', async () => {
    // Create a user
    const createResponse = await axios.post(`${STAGING_URL}/createUser`, {
        name: 'E2E Test User',
        email: `e2e-${Date.now()}@test.com`
    });
    expect(createResponse.status).toBe(201);
    const { userId } = createResponse.data;

    // Retrieve the user
    const getResponse = await axios.get(`${STAGING_URL}/getUser?userId=${userId}`);
    expect(getResponse.status).toBe(200);
    expect(getResponse.data.name).toBe('E2E Test User');

    // Cleanup
    await axios.delete(`${STAGING_URL}/deleteUser?userId=${userId}`);
});

CI/CD Pipeline

Here's a GitHub Actions workflow that runs all three test layers:

name: Cloud Functions Tests

on: [push, pull_request]

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm ci
      - run: npm test -- --testPathPattern=unit

  integration-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - uses: actions/setup-java@v3
        with:
          java-version: '11'
          distribution: 'temurin'
      - run: npm install -g firebase-tools
      - run: npm ci
      - run: firebase emulators:exec --only functions,firestore,pubsub "npm test -- --testPathPattern=integration"
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}

Monitoring in Production

Even with excellent local tests, production cloud functions encounter edge cases that tests don't cover — unexpected payload shapes, third-party API timeouts, quota exhaustion. Tools like HelpMeTest let you continuously run tests against your deployed functions, catching regressions before your users do. Setting up synthetic monitors on your critical HTTP function endpoints gives you an early warning system that complements your CI test suite.

Common Gotchas

Cold start latency: The emulator doesn't simulate cold starts. If your function has expensive initialization (loading ML models, establishing connection pools), test the initialization path explicitly in a separate test.

Event shape differences: The Functions Framework and Firebase emulators generate realistic event shapes, but verify against the official Cloud Functions event format documentation if your tests are failing on event parsing.

Authentication in integration tests: The emulator doesn't enforce Firebase Auth by default. Add firebase-admin auth mock for functions that check authentication status.

Idempotency: Background functions should be idempotent — Pub/Sub delivers at-least-once. Write tests that invoke the handler twice with the same event and assert no duplicate side effects.

Timeout handling: GCF HTTP functions have a maximum timeout (default 60 seconds). Write tests that simulate slow downstream calls to verify your timeout handling works correctly.

With this layered testing approach — fast unit tests, local emulator integration tests, and targeted E2E tests in staging — you can ship Google Cloud Functions with confidence that they work in production.

Read more

Start now free