Contract tests for NestJS APIs and clients
Use OpenAPI compatibility checks to detect structural changes, then exercise real NestJS endpoints and representative clients to verify behavior. Include validation, authorization, pagination, idempotency, and error contracts. A schema that parses successfully does not prove that an integration still works.
Inside this article 5 sections +
An OpenAPI document can remain valid while an API breaks its clients. A field may become required at runtime but remain optional in the schema. A serializer may omit a property the generated client expects. An endpoint can return the same shape while changing the meaning of a conflict response.
For a NestJS application, test three connected contracts: the published schema, the running HTTP behavior, and the behavior of supported clients. Each catches a different class of failure. Together they provide useful evidence that a change can be released without forcing every consumer to upgrade immediately.
Keep schema, runtime, and consumer evidence separate
Generate the OpenAPI document from the application configuration used for the contract test. Include the actual global prefix, versioning, authentication scheme, and relevant DTO metadata. Compare the result with the supported baseline using a tool whose compatibility rules match your API policy.
The schema comparison can identify removed fields, changed types, new required inputs, and altered response definitions. It cannot establish that the controller, validation pipe, guard, and serializer actually follow that document. Run HTTP-level tests against the assembled NestJS application to verify those boundaries.
- OpenAPI document
- Are operations, types, required fields, and responses compatible with the published contract?
- Running NestJS API
- Do pipes, guards, controllers, and serializers implement that contract?
- Representative client
- Can the supported client interpret the response and complete its business workflow?
Use the generated client version that customers actually support, not only a client regenerated from the proposed schema. A new API and newly generated client can agree with each other while both have moved away from the old contract. Keep at least one compatibility fixture for the oldest supported consumer behavior.
Test the exact validation policy
Record the global ValidationPipe options used in production. Transformation, whitelisting, and rejection of unexpected properties affect the observable API. A test application that omits those options can accept input that production rejects, or fail to catch a production-only conversion.
Exercise missing values, explicit nulls, empty strings, numeric strings, unexpected fields, and nested objects. Whether each is accepted depends on the intended contract. Do not assume TypeScript types enforce network input at runtime, and do not assume every schema annotation automatically supplies the validation rule you need.
Check output serialization as well. Entity objects, class transformations, and manually constructed responses can expose different fields. Assert that internal account identifiers, persistence metadata, and sensitive properties are absent when the public contract excludes them. A successful type check does not prevent accidental extra data in JSON.
Build fixtures around a meaningful operation
Use an illustrative subscription update that requires an expected revision and idempotency key. The happy path changes the subscription once and returns its canonical revision. The useful failure cases include stale input, missing permission, duplicate intent, and a response lost after commit.
| Scenario | HTTP evidence | Business evidence |
|---|---|---|
| Valid expected revision | Documented success representation | One committed revision change |
| Stale revision | Stable conflict code and useful detail | No overwrite of newer state |
| Repeated operation identity | Defined replay or in-progress response | No second subscription effect |
| Another tenant's identifier | Documented access-denial behavior | No cross-tenant read or mutation |
Use synthetic account fixtures and reset them deliberately. Avoid a shared mutable test account whose revision changes unpredictably across parallel jobs. Namespace operations by test run while keeping the scenario deterministic enough to diagnose a failure.
Exercise the generated client as a consumer
Compile a small client fixture against the supported generated package, call the test API, and assert the application-level result. Include enum handling, optional fields, dates, pagination tokens, and error parsing. These are common places where a structurally acceptable response becomes awkward or unusable for a real client.
Illustrative consumer scenario, not framework-specific code:
load subscription and remember revision
submit change using that revision and a stable operation key
parse canonical result through the supported client
repeat the same intent
assert one business change and a compatible replay result
submit a different body under the same key
assert the documented conflict classification
Do not write a client fixture that reproduces the server implementation line for line. Its purpose is to express what a consumer needs, including failure decisions. If the client treats a particular code as retryable, verify that code only appears for outcomes where retrying under the contract is appropriate.
Include content negotiation and response headers when clients depend on them. A generated body schema will not catch a missing pagination header, an unexpected content type, or a cache directive that makes private account data reusable in the wrong context. Test these properties through the same HTTP adapter and proxy assumptions used by the deployed API.
Make compatibility failures reviewable
Store the schema diff and failed fixture evidence with the change. A breaking change can be intentional, but it needs a versioning or migration decision rather than a blanket update of every snapshot. Keep the supported baseline explicit so reviewers know which consumers the gate protects.
Separate nondeterministic fields before snapshot comparison, and prefer targeted assertions for behavior. A giant JSON snapshot can hide a significant semantic change among formatting noise. Record request and response examples with secrets and personal data removed.
The API versioning guide explains coexistence, while NestJS module design places business rules behind a clear boundary. API implementation should deliver compatibility evidence that both engineers and integration owners can understand.