Skip to content

Phase 4, Task 2: Unit Tests Completion #33

@Sam-Bolling

Description

@Sam-Bolling

Task

Complete unit test coverage for the CSAPIQueryBuilder class and helper functions by adding edge case tests, error case tests, pagination tests, and query parameter tests to achieve >80% statement and branch coverage for all CSAPI core modules.

ROADMAP Reference: Phase 4, Task 2 — Unit Tests Completion (~3-4 hours, Medium complexity)


Files to Create or Modify

File Action Est. Lines Purpose
src/ogc-api/csapi/url_builder.spec.ts Modify ~200-300 Add edge case, error, pagination, and query parameter tests to existing QueryBuilder test suite
src/ogc-api/csapi/helpers.spec.ts Modify ~100-150 Complete coverage for all exported helper functions

Total: ~300-450 lines of additional test code across 2 files

Blueprint Reference

Follow the EDR test pattern in src/ogc-api/edr/model.spec.ts (42 lines) — uses Jest describe/test blocks, direct function imports, and assertion-per-behavior style. Also follow the upstream src/ogc-api/endpoint.spec.ts for integration-style unit test patterns with globalThis.fetch mocking.

Scope — What to Implement

1. QueryBuilder Edge Case Tests (url_builder.spec.ts)

Add tests for boundary conditions not covered by the per-resource method tests written in Phase 2 (Issues #5-#13):

Empty/minimal collections:

  • Collection with zero available resources → all methods throw EndpointError
  • Collection with exactly one resource type → only that resource's methods work
  • Minimal resource responses (required fields only, no optional fields)

Boundary conditions:

  • limit at boundaries: 0, 1, maximum allowed value
  • offset at boundaries: 0, negative (should error), very large values
  • bbox edge cases: antimeridian crossing, zero-area bbox, reversed coordinates
  • datetime edge cases: open-ended intervals (../end, start/..), single instant, far-future/far-past dates
  • Empty string parameters: id: '', parentId: ''

Resource validation edge cases:

  • Calling a method for a resource the server doesn't advertise
  • Resource availability check with malformed conformance data
  • Mixed-case or unexpected resource type strings

2. Error Case Tests (url_builder.spec.ts)

Invalid parameters:

  • Missing required parameters (e.g., getSystem() without an ID)
  • Wrong parameter types (number where string expected)
  • Malformed URLs (invalid characters, double slashes, missing protocol)
  • Invalid temporal formats (non-ISO 8601 strings)

Resource validation failures:

  • EndpointError thrown with correct message and available resources list
  • Error message includes collection ID and unavailable resource type
  • availableResources Set is correctly populated from conformance data

Network-adjacent error handling:

  • Malformed server responses during builder initialization
  • Missing or invalid conformance document

3. Pagination Tests (url_builder.spec.ts)

Offset-based pagination:

  • limit and offset parameters correctly appended to URLs
  • Default values when pagination parameters omitted
  • Combined with other query parameters (bbox + limit + offset)

Cursor-based pagination:

  • Cursor token correctly appended to URL
  • Cursor combined with limit parameter
  • Invalid cursor format handling

4. Query Parameter Tests (url_builder.spec.ts)

Verify correct URL encoding for ALL query parameter categories:

Spatial parameters:

  • bbox with 4 values (2D) and 6 values (3D)
  • geom with WKT string encoding
  • lat/lon/radius for proximity queries

Temporal parameters:

  • datetime with single instant, bounded interval, open-ended interval
  • phenomenonTime, resultTime, validTime for observation queries
  • ISO 8601 format validation

Relationship parameters:

  • parent, procedure, foi, observedProperty — correct URL encoding
  • Multiple relationship filters combined

Hierarchical parameters:

  • recursive flag correctly appended
  • Combined with parent/system filters

Format parameters:

  • f (format) parameter for content negotiation
  • Multiple format values

5. Helper Function Tests (helpers.spec.ts)

Complete coverage for all exported helper functions:

URL building helpers:

  • buildResourceUrl() — all path segment combinations
  • buildQueryString() — parameter encoding, special characters, empty params
  • URL encoding of special characters in IDs (slashes, spaces, unicode)

Temporal helpers:

  • ISO 8601 parsing for all valid formats
  • Edge cases: midnight, timezone handling, duration formats

Validation helpers:

  • extractAvailableResources() from conformance data
  • Malformed conformance payloads
  • Missing or partial conformance data

Note: Per the Guide (L622), buildResourceUrl, buildQueryString, and extractAvailableResources are currently private helpers tested indirectly through public API tests. If they remain private when this task begins, add more public-API tests covering their edge cases. If they have been extracted as exported functions by then, add direct unit tests here.

JSDoc Requirements

  • Document all test describe blocks with a summary of what coverage category they provide
  • Add @see links to the relevant query parameter documentation in the Guide (§6 Query Parameters Reference)
  • Follow the JSDoc style in src/ogc-api/edr/model.spec.ts

Testing Requirements

  • Modify src/ogc-api/csapi/url_builder.spec.ts (~200-300 additional lines)
  • Modify src/ogc-api/csapi/helpers.spec.ts (~100-150 additional lines)
  • All tests use globalThis.fetch = jest.fn() mocking — no nock, msw, or other libraries
  • Every test must validate meaningful client behavior (URL correctness, error messages, validation logic) — not trivial assertions (AP4/AP1 compliance)
  • Follow test patterns from src/ogc-api/edr/model.spec.ts (42 lines)
  • Run npm test — all existing + new tests pass
  • Run coverage report — >80% statement and branch coverage for url_builder.ts, model.ts, helpers.ts

Scope — What NOT to Touch

  • ❌ Do NOT add integration tests — those belong to Phase 4, Task 1: Integration Tests #31 (Phase 4, Task 1: Integration Tests)
  • ❌ Do NOT add format parser tests — those were written incrementally in Phase 3 (Issues Phase 3.1: GeoJSON Handler Extensions #14-Phase 3, Task 17: Format Index #30)
  • ❌ Do NOT modify implementation files (url_builder.ts, model.ts, helpers.ts) — if a bug is discovered, document it as a separate issue
  • ❌ Do NOT add new test fixtures — reuse fixtures created in Phases 1-3
  • ❌ Do NOT modify API documentation or JSDoc in implementation files — that belongs to Phase 4, Task 3: API Documentation #32 (GitHub) / Phase 4, Task 3: API Documentation
  • ❌ Do NOT modify files outside the "Files to Create or Modify" table above
  • ❌ Do NOT refactor existing test code unless required to complete this task
  • ❌ Do NOT write tests that assert fixture data values (AP1 violation) or data shape (AP4 violation)

Acceptance Criteria

  • url_builder.spec.ts has additional edge case tests (~200-300 new lines)
  • helpers.spec.ts has complete coverage for all exported helpers (~100-150 new lines)
  • Edge case tests cover: empty collections, boundary values, minimal resources
  • Error case tests cover: invalid parameters, malformed URLs, resource validation failures
  • Pagination tests cover: offset-based and cursor-based modes, combined with other params
  • Query parameter tests cover: all spatial, temporal, relationship, hierarchical, format parameters
  • All new tests follow meaningful-test standard (no AP1/AP4 violations)
  • All new code has JSDoc documentation
  • Existing tests still pass (npm test)
  • >80% statement and branch coverage for CSAPI core modules
  • No lint errors

Dependencies

Blocked by: #31 — Phase 4, Task 1: Integration Tests (integration test infrastructure must exist first)
Blocks: #32 (GitHub) — Phase 4, Task 3: API Documentation (all tests must pass before final doc review)


Operational Constraints

⚠️ MANDATORY: Before starting work on this issue, review docs/governance/AI_OPERATIONAL_CONSTRAINTS.md.

Key constraints for this task:

  • Precedence: OGC specifications → AI Collaboration Agreement → This issue description → Existing code → Conversational context
  • No scope expansion: Do not infer unstated requirements or add unrequested features
  • No refactoring: Do not rename, restructure, or "improve" code outside this issue's scope
  • Minimal diffs: Prefer the smallest change that satisfies the acceptance criteria
  • Ask when unclear: If intent is ambiguous, stop and ask for clarification
  • Anti-patterns: All tests must comply with AP1-AP5 (see Guide §Development Standards)

References

Read these documents before starting implementation. They are ordered by priority.

Primary References (must read)

# Document Section/Lines What It Provides
1 docs/planning/csapi-implementation-guide.md §9 Testing Components (L3275-3375) Complete test coverage specification — all test suites, fixture requirements, scope exclusions, HTTP mocking convention
2 docs/planning/csapi-implementation-guide.md §6 Query Parameters Reference (L1943+) All query parameter definitions — needed for query parameter test design
3 docs/planning/csapi-implementation-guide.md §14 Code Volume Summary — Test Files (L4333-4342) Test file counts and line estimates
4 src/ogc-api/edr/model.spec.ts Full file (42 lines) Test style blueprint — describe/test blocks, assertion patterns
5 docs/planning/ROADMAP.md Phase 4, Task 2 (L577-585) Task definition and deliverables

Upstream Type/Import References (files this task tests)

# Document What to Test
1 src/ogc-api/csapi/url_builder.ts All 80 CSAPIQueryBuilder methods — edge cases, errors, pagination
2 src/ogc-api/csapi/helpers.ts All exported helper functions — URL building, temporal parsing, validation
3 src/ogc-api/csapi/model.ts Type definitions used in test assertions

Research References (context, not required reading)

# Document What It Provides
1 docs/research/testing/findings/06-meaningful-vs-trivial-definition.md Definition of meaningful vs trivial tests — enforcement standard
2 docs/research/testing/review/phase-0-lessons-from-failed-attempt.md AP1-AP5 anti-pattern definitions with examples and remediation
3 docs/research/testing/testing-strategy-research.md Overall testing strategy and coverage targets

Specification References (for @see links and test accuracy)

# Document Use
1 OGC API - Connected Systems Part 1 (23-001) Part 1 endpoint definitions and query parameters for URL validation tests
2 OGC API - Connected Systems Part 2 (23-002) Part 2 endpoint definitions, observation/command query parameters
3 docs/research/standards/ogcapi-connectedsystems-1.bundled.oas31.yaml Part 1 OpenAPI spec — exact query parameter names and types
4 docs/research/standards/ogcapi-connectedsystems-2.bundled.oas31.yaml Part 2 OpenAPI spec — exact query parameter names and types

Convention Quick Reference

Rule Example
Use .js extension for relative imports import { X } from './file.js'
Use import type for interfaces/types import type { Y } from './model.js'
Three-tier hierarchy: import from lower tiers only shared → ogc-api → csapi
Named exports for types and utilities export interface Z { ... }
as const arrays for enum-like values export const XTypes = [...] as const
HTTP mocking: globalThis.fetch = jest.fn() Never use nock, msw, or other libraries
Meaningful tests only Verify behavior, not that code runs without throwing

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions