firebase-functions

Firebase Functions Development Standards

These rules apply when working with Firebase Cloud Functions.

CRITICAL: TDD Requirement

All changes MUST follow Test-Driven Development:

  1. Write a failing test first
  2. Write minimal code to make it pass
  3. Refactor while keeping tests green
  4. No code changes without corresponding tests

Fakes Over Mocks

Use fakes that you control, not mocks that verify interactions.

Example fake pattern:

class FakeStripeWrapper {
    result = null;
    error = null;
    calledWith = null;

    async createCustomer(params) {
        if (this.error) throw this.error;
        this.calledWith = params;
        return this.result;
    }
}

Control what it returns, assert on outcomes.

Test Outcomes, Not Interactions

Fragile - tests implementation details:

// WRONG
expect(mockStripe.createCustomer).toHaveBeenCalledWith(params);

Better - tests observable outcomes:

// RIGHT
const result = await createStripeCustomer(userId, email);
expect(result.customerId).toBeDefined();
expect(fakeFirebase.savedCustomer.email).toBe(email);

Working Directory

cd firebase/functions

Common Commands

npm ci          # Install dependencies
npm test        # Run tests
npm run test-ci # Run tests with CI reporting
npm run stryker # Run mutation tests
npm run lint    # Check linting
npm run lintfix # Fix linting issues
npm run serve   # Start local emulator
npm run deploy  # Deploy to Firebase
npm run logs    # View logs

TDD Workflow

# 1. Write failing test first
npx mocha test/your_feature.spec.js --grep "your test name"

# 2. See it fail (red)
# 3. Write minimal code to pass
# 4. Run test again - should pass (green)
# 5. Refactor if needed, keeping tests green
# 6. Run full test suite before committing
npm test

Running Single Tests

npx mocha test/specific_test.spec.js
npx mocha --grep "pattern"

Architecture

Entry Point: index.js - Exports all cloud functions

Core Modules:

Key Functions

Testing Standards

Code Style