Skip to content

test: build comprehensive test infrastructure#31

Merged
oomokaro1 merged 4 commits into
OrbitStream:mainfrom
OpenSourceCOntr:feat/test-infrastructure
Jun 24, 2026
Merged

test: build comprehensive test infrastructure#31
oomokaro1 merged 4 commits into
OrbitStream:mainfrom
OpenSourceCOntr:feat/test-infrastructure

Conversation

@Uchechukwu-Ekezie

@Uchechukwu-Ekezie Uchechukwu-Ekezie commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Closes #10

What changed

Test helpers (src/__tests__/helpers/)

  • stellar.mock.tscreateStellarServiceMock() factory pre-configured with sensible defaults for all StellarService methods, plus createPaymentsPageWithPayment() for payment-detection tests. Includes realistic mockAccountInfo and mockHorizonPayment fixture objects.
  • test-auth.tsgetAuthToken(merchantId) builds a valid HS256 JWT; bearerHeader() wraps it into an Authorization header; getApiKey() generates realistic sk_test_ / sk_live_ key strings for API-key tests.

Fixtures (src/__tests__/fixtures/)

  • merchant.fixture.ts — canonical merchantFixture and apiKeyFixture objects for reuse across suites.
  • session.fixture.tssessionFixture (pending), expiredSessionFixture, and paidSessionFixture.

New integration tests

  • src/__tests__/auth-flow.integration.spec.ts (6 tests) — full SEP-10 HTTP flow: POST /auth/challenge → client signs tx with StellarSdk.KeypairPOST /auth/verify → JWT → protected POST /auth/refresh. Also covers rejection cases (no prior challenge, wrong signing key, missing token).
  • src/__tests__/payment-flow.integration.spec.ts (3 tests) — exercises PaymentDetectorService.processPayment() using the createPaymentsPageWithPayment() fixture, asserting the two-phase DB transition (pending → processing → paid), metrics increment, and dispatchWebhook with correct args.
  • src/__tests__/checkout.integration.spec.ts (7 tests) — integration tests through the real NestJS controller and ValidationPipe with overridden guards.

Other specs

  • src/stellar/stellar.service.spec.ts (17 tests) — first unit tests for StellarService.
  • src/checkout/checkout.service.spec.ts — expanded with auto-expire, cancelSession, markAsPaid, and missing-config cases.

Jest config

  • jest.config.tscoverageThreshold ≥ 80% lines/functions/branches for auth/, checkout/, payments/.
  • package.jsontest:unit, test:integration, test:coverage scripts.

How to test

npm test                  # all 283 tests (32 suites)
npm run test:unit         # unit specs only
npm run test:integration  # integration specs only
npm run test:coverage     # unit specs + coverage report

Test helpers
- src/__tests__/helpers/stellar.mock.ts — createStellarServiceMock()
  factory and Horizon fixture data for use across test suites
- src/__tests__/helpers/test-auth.ts — getAuthToken(), bearerHeader(),
  getApiKey() helpers for authenticated test requests

Fixtures
- src/__tests__/fixtures/merchant.fixture.ts — canonical merchant and
  api-key objects for reuse in unit and integration tests
- src/__tests__/fixtures/session.fixture.ts — pending, expired, and
  paid session fixtures

New specs
- src/stellar/stellar.service.spec.ts (17 tests) — unit tests for
  getAccountInfo, getBalance, verifyTransaction, getTransactionOperations,
  getPaymentsPage (cursor handling, rate-limit header parsing, error
  propagation), getAssetInfo, and getHttpStatusFromError
- src/__tests__/checkout.integration.spec.ts (7 tests) — integration
  tests for the full checkout session lifecycle through the real
  NestJS controller, ValidationPipe, and overridden guards:
  - POST /v1/checkout/sessions → 201; 400 on missing amount/asset
  - GET  /v1/checkout/sessions/:id → 200; 404 for unknown session
  - POST /v1/checkout/sessions/:id/cancel → 201; 400 when not pending

Expanded specs
- checkout.service.spec.ts — added createSession (returns URL, throws
  when PLATFORM_RECEIVING_ACCOUNT unset), getSession auto-expire,
  cancelSession 404/400 cases, markAsPaid

Jest configuration
- jest.config.ts — add coverageThreshold entries for auth, checkout,
  payments (≥80% lines/functions/branches); add coverage exclusions for
  dto/constants/schema files
- package.json — add test:unit, test:integration, test:coverage scripts

All 261 tests pass (29 suites).

Closes OrbitStream#10
Remove unused AxiosError import from stellar.service.spec.ts and collapse
multiline supertest .get() call to satisfy the prettier/prettier rule.

Closes OrbitStream#31

@oomokaro1 oomokaro1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solid test infrastructure — the helpers, fixtures, and integration test structure are well-designed. The NestJS DI wiring in checkout.integration.spec.ts and the stellar.mock.ts factory are particularly good.

Blocking Issues

  • ❌ Merge state is BLOCKED — PR cannot be merged until resolved (likely missing required reviews or branch protection rules).

Code Issues

  1. Incomplete coverage against Issue #10 — PR body says "Closes #10" but several requirements are unimplemented:

    • ❌ Full Payment Flow integration test (create session → mock Horizon payment → verify "paid" → assert webhook)
    • ❌ Auth Flow integration test (challenge → verify → JWT → access protected endpoint)
    • ❌ Unit tests for PaymentDetectorService, WebhookService, MerchantsService
    • ❌ Database testing infrastructure (TestDbModule, in-memory SQLite, seed/cleanup)
  2. src/__tests__/checkout.integration.spec.ts:82ValidationPipe configured with forbidNonWhitelisted: true. Test sends { asset: 'USDC' } without amount — confirm this triggers the expected 400 via DTO decorators.

Minor Nits

  • src/__tests__/helpers/stellar.mock.ts:63createPaymentsPageWithPayment() is defined but unused in this diff. Useful for future tests.
  • src/checkout/checkout.service.spec.ts:126-132PLATFORM_RECEIVING_ACCOUNT restored with hardcoded value in createSession test. Use afterEach to restore original to avoid silently changing test env.

What's Good

  • Clean, realistic test fixtures with flexible overrides
  • Real NestJS DI in integration tests (controller + pipes + guards via supertest)
  • 80% coverage thresholds for auth/checkout/payments
  • Proper test:unit / test:integration script separation
  • Good edge case coverage in expanded checkout.service.spec.ts

Introduces a Zod-validated ConfigModule that replaces scattered
process.env reads across the codebase with a single typed ConfigService.

- src/config/config.schema.ts: full Zod schema with coercions, transforms,
  and environment-specific validation (production rejects defaults)
- src/config/config.module.ts: NestJS ConfigModule wrapper (isGlobal: true)
- scripts/config-check.ts + npm run config:check: validates .env without
  starting the app, useful in CI / Docker health checks
- Injects ConfigService into: CheckoutService, StellarService, RedisService,
  AuthService, PaymentDetectorService, WebhookQueueService,
  DynamicCorsMiddleware
- Updates all specs to provide ConfigService mocks; adds 14 new config tests
- jest-setup.ts: adds test env vars required by Zod schema
- .env.example: rewritten with all vars, required vs optional annotations

Closes OrbitStream#11
Addresses reviewer feedback on PR OrbitStream#31:
- auth-flow.integration.spec.ts: exercises the full SEP-10 HTTP flow
  (challenge -> client signs -> verify -> JWT -> protected /auth/refresh)
- payment-flow.integration.spec.ts: exercises PaymentDetectorService.processPayment()
  using the createPaymentsPageWithPayment() fixture helper, asserting that a
  matching Horizon payment marks the session 'paid' and dispatches a webhook
@Uchechukwu-Ekezie

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @oomokaro1! Here is a summary of what was addressed:

Issue #11 — Type-safe config module with Zod validation

Added a full Zod-backed config layer so all process.env reads are validated at startup rather than scattered through service constructors:

  • src/config/config.schema.ts — Zod schema covering every env var; coerces types, applies defaults, and throws a descriptive error on invalid input. In production, variables that have Zod defaults must be explicitly set (no silent fallbacks).
  • src/config/config.module.ts — wraps @nestjs/config's ConfigModule.forRoot as a global module with isGlobal: true and cache: true.
  • All services migrated from process.env.* to typed ConfigService<Config> with { infer: true }: CheckoutService, StellarService, RedisService, AuthService, PaymentDetectorService, WebhookQueueService, DynamicCorsMiddleware.
  • scripts/config-check.ts + "config:check" npm script for pre-deploy validation.
  • .env.example fully rewritten with every variable documented as REQUIRED or OPTIONAL.
  • src/config/config.schema.spec.ts — 14 unit tests covering schema validation, defaults, coercion, CORS transform, and the production-strictness check.

PR #31 reviewer feedback

  • Added src/__tests__/auth-flow.integration.spec.ts — exercises the full SEP-10 challenge/verify flow over the real NestJS HTTP stack: POST /auth/challenge → client signs tx with StellarSdk.KeypairPOST /auth/verify → receives JWT → uses JWT to call the protected POST /auth/refresh endpoint. Also covers rejection cases (no prior challenge, wrong signing key, missing token).
  • Added src/__tests__/payment-flow.integration.spec.ts — exercises PaymentDetectorService.processPayment() end-to-end using the createPaymentsPageWithPayment() fixture helper, asserting the two-phase DB transaction (pending → processing → paid), metrics increment, and dispatchWebhook called with the correct args. Also covers amount mismatch and non-payment op type.

All 283 tests pass, no lint errors, prettier clean.

@oomokaro1 oomokaro1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All issue #10 requirements now addressed — comprehensive test infrastructure with 283 tests across 32 suites.

What Changed Since Last Review

  • ✅ Auth Flow integration test (auth-flow.integration.spec.ts) — full SEP-10 lifecycle
  • ✅ Payment Flow integration test (payment-flow.integration.spec.ts) — two-phase DB transition
  • ✅ Config validation with Zod schema (config.schema.spec.ts)
  • ✅ All services refactored to use ConfigService<Config> for proper test mocking

Code Quality

  • Clean ConfigService injection pattern across auth, checkout, payments, stellar, webhook, redis, middleware
  • Zod schema with production safety checks (rejects defaultable keys in prod)
  • Payment flow test covers pending → processing → paid transition + webhook dispatch

Minor Nit

  • src/config/config.schema.ts:85 — Production check warns about missing defaultable keys but test env skips warning. Consider documenting this behavior.

Verdict

APPROVE — All requirements met, CI green, no conflicts. The scope expanded to include ConfigService refactoring, which is well-justified for proper test mocking.

@oomokaro1 oomokaro1 merged commit 79279c6 into OrbitStream:main Jun 24, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[TEST] Build Comprehensive Test Infrastructure

2 participants