Testing Google Cloud Run Services: Local and Integration Testing
Google Cloud Run turns any containerized application into a scalable, fully managed service. But that flexibility comes with testing complexity: your service might handle HTTP requests, Pub/Sub push messages, Cloud Scheduler events, or Eventarc triggers — each with a different invocation model. Testing all of these reliably, without incurring Cloud Run costs or depending on a live GCP project for every developer, requires a deliberate strategy.
This guide covers local testing with Docker and the Functions Framework, integration testing against deployed staging environments, and patterns for testing the most common Cloud Run backing services: Pub/Sub and Firestore.
Testing Cloud Run Containers Locally with Docker
A Cloud Run service is a container that handles HTTP requests. The simplest test environment is just Docker:
# Build the image
docker build -t my-service .
# Run it locally
docker run -p 8080:8080 \
-e PORT=8080 \
-e GOOGLE_CLOUD_PROJECT=my-project \
my-serviceCloud Run injects PORT at runtime. Your service must listen on that port. A minimal Node.js service:
// server.js
import express from "express";
const app = express();
app.use(express.json());
app.post("/process", async (req, res) => {
const { message } = req.body;
if (!message) return res.status(400).json({ error: "Missing message" });
// business logic here
res.json({ processed: true, length: message.length });
});
const port = parseInt(process.env.PORT || "8080");
app.listen(port, () => console.log(`Listening on port ${port}`));Run a quick smoke test against the local container:
curl -X POST http://localhost:8080/process \
-H "Content-Type: application/json" \
-d '{"message": "hello"}'
# {"processed":true,"length":5}For automated tests against the local container, use Docker Compose:
# docker-compose.test.yml
version: "3.8"
services:
app:
build: .
ports:
- "8080:8080"
environment:
PORT: "8080"
GOOGLE_CLOUD_PROJECT: "test-project"
FIRESTORE_EMULATOR_HOST: "firestore:8080"
PUBSUB_EMULATOR_HOST: "pubsub:8085"
firestore:
image: gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators
command: gcloud emulators firestore start --host-port=0.0.0.0:8080
ports:
- "8081:8080"
pubsub:
image: gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators
command: gcloud emulators pubsub start --host-port=0.0.0.0:8085
ports:
- "8085:8085"docker compose -f docker-compose.test.yml up -d
npm run test:integration
docker compose -f docker-compose.test.yml downUsing the Cloud Functions Framework for HTTP and Event Testing
If your Cloud Run service uses the Functions Framework, you get structured local testing support:
npm install @google-cloud/functions-framework// functions/processMessage.js
import { http, CloudEvent } from "@google-cloud/functions-framework";
http("processMessage", (req, res) => {
const { body } = req;
if (!body.text) return res.status(400).json({ error: "Missing text" });
res.json({ result: body.text.toUpperCase() });
});Run locally:
npx functions-framework --target=processMessage --port=8080The Functions Framework also supports CloudEvents for Eventarc testing:
import { cloudEvent } from "@google-cloud/functions-framework";
cloudEvent("onFileUploaded", (event) => {
const { bucket, name } = event.data;
console.log(`Processing ${name} from ${bucket}`);
});Test CloudEvents locally:
curl -X POST http://localhost:8080 \
-H "Content-Type: application/json" \
-H "ce-specversion: 1.0" \
-H "ce-type: google.cloud.storage.object.v1.finalized" \
-H "ce-source: //storage.googleapis.com/projects/_/buckets/my-bucket" \
-H "ce-id: test-event-1" \
-d '{"bucket":"my-bucket","name":"uploads/file.csv"}'For unit tests, import the function directly without the framework:
// functions/processMessage.test.js
import { handler } from "./processMessage.js";
function makeReq(body) {
return { body };
}
function makeRes() {
const res = {};
res.status = (code) => { res.statusCode = code; return res; };
res.json = (data) => { res.body = data; return res; };
return res;
}
test("returns 400 for missing text", () => {
const req = makeReq({});
const res = makeRes();
handler(req, res);
expect(res.statusCode).toBe(400);
});
test("returns uppercased text", () => {
const req = makeReq({ text: "hello" });
const res = makeRes();
handler(req, res);
expect(res.body.result).toBe("HELLO");
});Using the GCP Emulator Suite
The Google Cloud SDK ships emulators for Firestore, Pub/Sub, Bigtable, Datastore, and Spanner. Use them for local integration tests without touching real GCP resources.
Firestore Emulator
Start the emulator:
gcloud emulators firestore start --host-port=localhost:8080Or in code (using the @firebase/testing package):
import { initializeApp } from "firebase/app";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
const app = initializeApp({ projectId: "test-project" });
const db = getFirestore(app);
connectFirestoreEmulator(db, "localhost", 8080);Write Firestore integration tests:
// tests/firestore.test.js
import { getFirestore, connectFirestoreEmulator, doc, setDoc, getDoc } from "firebase/firestore";
import { initializeApp, deleteApp } from "firebase/app";
let app, db;
beforeEach(async () => {
app = initializeApp({ projectId: "test-project" }, `test-${Date.now()}`);
db = getFirestore(app);
connectFirestoreEmulator(db, "localhost", 8080);
});
afterEach(async () => {
await deleteApp(app);
});
test("stores and retrieves a document", async () => {
await setDoc(doc(db, "orders", "test-1"), { userId: "u1", total: 42 });
const snap = await getDoc(doc(db, "orders", "test-1"));
expect(snap.data()).toEqual({ userId: "u1", total: 42 });
});Clear emulator data between tests using the REST API:
afterEach(async () => {
await fetch(
"http://localhost:8080/emulator/v1/projects/test-project/databases/(default)/documents",
{ method: "DELETE" }
);
});Pub/Sub Emulator
gcloud emulators pubsub start --host-port=localhost:8085
export PUBSUB_EMULATOR_HOST=localhost:8085// tests/pubsub.test.js
import { PubSub } from "@google-cloud/pubsub";
const pubsub = new PubSub({ projectId: "test-project" });
// PUBSUB_EMULATOR_HOST env var routes all calls to the emulator
let topic, subscription;
beforeAll(async () => {
[topic] = await pubsub.createTopic("test-orders");
[subscription] = await topic.createSubscription("test-orders-sub");
});
afterAll(async () => {
await subscription.delete();
await topic.delete();
});
test("message is published and received", async () => {
const received = [];
subscription.on("message", (msg) => {
received.push(JSON.parse(msg.data.toString()));
msg.ack();
});
await topic.publishMessage({
data: Buffer.from(JSON.stringify({ orderId: "o1", amount: 99 })),
});
await new Promise(r => setTimeout(r, 500));
subscription.removeAllListeners("message");
expect(received).toContainEqual({ orderId: "o1", amount: 99 });
});Integration Tests Against Deployed Staging Services
Local emulators are great for development but can miss real GCP behavior. For pre-merge gates, run integration tests against a dedicated staging Cloud Run service.
Deploy a staging service via gcloud:
gcloud run deploy my-service-staging \
--image gcr.io/my-project/my-service:$COMMIT_SHA \
--region us-central1 \
--no-allow-unauthenticated \
--set-env-vars="ENV=staging"Get the service URL and run tests:
SERVICE_URL=$(gcloud run services describe my-service-staging \
--region us-central1 --format "value(status.url)")
SERVICE_URL=$SERVICE_URL npm run test:integrationFor authenticated Cloud Run services, get an ID token:
// tests/helpers/auth.js
import { GoogleAuth } from "google-auth-library";
export async function getIdToken(audience) {
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(audience);
const headers = await client.getRequestHeaders();
return headers.Authorization;
}// tests/integration/service.test.js
import { getIdToken } from "./helpers/auth.js";
const BASE_URL = process.env.SERVICE_URL;
test("authenticated request returns 200", async () => {
const token = await getIdToken(BASE_URL);
const res = await fetch(`${BASE_URL}/process`, {
method: "POST",
headers: {
"Authorization": token,
"Content-Type": "application/json",
},
body: JSON.stringify({ text: "hello" }),
});
expect(res.status).toBe(200);
});Testing Pub/Sub Push Subscriptions
Cloud Run is commonly triggered by Pub/Sub push subscriptions. The subscription sends HTTP POST requests to your service URL. Test this locally by simulating the push message format:
// The exact format Pub/Sub push sends to Cloud Run
const pubsubPushMessage = {
message: {
data: Buffer.from(JSON.stringify({ orderId: "o1" })).toString("base64"),
messageId: "test-message-id",
publishTime: new Date().toISOString(),
attributes: { source: "order-service" },
},
subscription: "projects/my-project/subscriptions/orders-sub",
};
test("handles Pub/Sub push message", async () => {
const res = await fetch("http://localhost:8080/pubsub", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(pubsubPushMessage),
});
expect(res.status).toBe(200);
});In your handler, decode the base64 data:
app.post("/pubsub", (req, res) => {
const { message } = req.body;
if (!message?.data) return res.status(400).send("Missing message data");
const data = JSON.parse(Buffer.from(message.data, "base64").toString());
console.log("Received:", data);
// Process the message
res.status(200).send("OK");
});Testing Cloud Scheduler Triggers
Cloud Scheduler sends HTTP requests on a schedule. Test the handler endpoint directly:
app.post("/scheduled/cleanup", async (req, res) => {
// Verify request comes from Cloud Scheduler
const oidcToken = req.headers.authorization?.split(" ")[1];
if (!oidcToken && process.env.NODE_ENV !== "test") {
return res.status(403).send("Unauthorized");
}
const deleted = await cleanupOldRecords();
res.json({ deleted });
});Unit test the cleanup logic separately, and test the endpoint:
test("cleanup endpoint returns count of deleted records", async () => {
jest.spyOn(db, "deleteOldRecords").mockResolvedValue(42);
process.env.NODE_ENV = "test";
const res = await fetch("http://localhost:8080/scheduled/cleanup", {
method: "POST",
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.deleted).toBe(42);
});CI Pipeline for Cloud Run Tests
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: "20" }
- run: npm ci && npm test
integration-tests:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- uses: google-github-actions/auth@v2
with:
credentials_json: ${{ secrets.GCP_SA_KEY }}
- uses: google-github-actions/setup-gcloud@v2
- name: Build and push image
run: |
gcloud builds submit --tag gcr.io/$PROJECT_ID/my-service:$GITHUB_SHA
env:
PROJECT_ID: ${{ vars.GCP_PROJECT_ID }}
- name: Deploy to staging
run: |
gcloud run deploy my-service-staging \
--image gcr.io/$PROJECT_ID/my-service:$GITHUB_SHA \
--region us-central1 \
--no-allow-unauthenticated
echo "SERVICE_URL=$(gcloud run services describe my-service-staging \
--region us-central1 --format 'value(status.url)')" >> $GITHUB_ENV
- run: npm run test:integration
env:
SERVICE_URL: ${{ env.SERVICE_URL }}Conclusion
Testing Cloud Run services well means combining multiple approaches. Use Docker locally for fast iteration without any GCP dependency. Use GCP emulators for Firestore and Pub/Sub to test service integrations without incurring costs. Use the Functions Framework for CloudEvent testing. And run a focused suite of integration tests against a dedicated staging deployment before merging to main.
The emulator-based approach keeps the inner dev loop fast while the staging integration tests give confidence that real GCP service behaviors — rate limits, consistency guarantees, IAM — work as expected.