Blog

    AI-Driven TDD with NestJS and Contract-First Testing: OpenAPI as the Source of Truth for Tests

    By GauravSeptember 24, 20269 mins read
    On this page

    AI-driven TDD with NestJS and contract-first testing starts from one file: the OpenAPI specification, written and reviewed before any controller exists. Types and mocks are generated from it, AI tools help write the first failing tests, and the specification decides what correct means.

    Startup founders and engineering leaders running TypeScript backends will find how the workflow runs, where AI helps and where it must not decide, and how to stop the code and the contract from drifting apart.

    What is AI-driven TDD with NestJS and contract-first testing?

    AI-driven TDD with NestJS and contract-first testing is a workflow where the OpenAPI specification is written and reviewed first, an AI assistant drafts failing tests from it, and developers then write NestJS code until those tests pass. The specification, not the AI and not the code, is the source of truth for every test.

    Moving a NestJS API to contract-first?

    We set up the specification, generated types, test pipeline and review gates for AI-drafted tests.

    Agnotic Technologies sets this workflow up for product teams that want faster test writing without letting a model decide what their API should do.

    Why put the OpenAPI specification first?

    Putting the OpenAPI specification first means product, frontend and backend agree on paths, payloads, errors and status codes before anyone builds.

    The OpenAPI Specification 3.1.0 defines a standard, language-agnostic interface to HTTP APIs that lets people and computers discover and understand a service's capabilities without access to source code, documentation or network traffic inspection. Its Schema Object is a superset of JSON Schema Draft 2020-12.

    Written first, the document becomes the place where design decisions are made and reviewed. Changes are pull requests to one file, discussed like any other code change.

    The NestJS documentation describes OpenAPI as a language-agnostic definition format for describing RESTful APIs, and says Nest provides a dedicated module, @nestjs/swagger, that generates such a specification from decorators in your code.

    That is code-first: the document describes what the code already does. Contract-first reverses the direction. The NestJS app can still generate its document, but only so CI can compare it with the designed one.

    Design-first or code-first: what changes?

    Design-first changes where decisions are made, where types come from and what tests are measured against.

    Code-first and contract-first NestJS APIs compared
    QuestionCode-firstContract-first
    Where the API is designedIn controllers and DTO decoratorsIn the OpenAPI file, reviewed before code
    Source of typesDTO classes written by handGenerated from the specification
    What tests check againstThe behaviour the developer intendedThe specification's schemas, status codes and examples
    When consumers can startAfter the endpoint existsAs soon as the specification merges, using mocks
    How drift is caughtBy reviewers, if at allA CI check comparing the generated document with the designed one

    How does the workflow run step by step?

    The workflow runs as a loop that begins in the specification and ends with a drift check in CI.

    • Step 1, design: add or change the operation in the OpenAPI file, with schemas, error responses and examples.
    • Step 2, review: frontend, backend and product approve the change in a pull request.
    • Step 3, generate: produce TypeScript types and a mock server from the merged file.
    • Step 4, draft tests: an AI assistant proposes failing tests for the operation from the specification.
    • Step 5, review tests: a developer checks each test against the specification and deletes guesses.
    • Step 6, implement: write the NestJS controller and service until the tests pass.
    • Step 7, check drift: CI compares the app's generated document with the designed file and fails on differences.

    One operation, worked through

    Take a single operation, POST /appointments, to see how the loop behaves in practice. The specification lists a 201 response with the created appointment, a 400 for an invalid request, and a 409 when the slot is already taken.

    • Specification: the request schema marks start time and clinician ID as required, and the duration as an integer with a minimum and maximum.
    • AI draft: the assistant proposes tests for each response, plus boundary tests for the duration limits.
    • Review: the developer deletes a drafted test that expected a 422, because the specification never mentions one.
    • Implementation: the controller and service are written until the remaining tests pass.
    • Drift check: CI generates the document from the NestJS decorators and confirms it matches the designed file.

    The deleted 422 test is the important moment. Either the specification is missing a case, in which case someone changes the specification first, or the AI guessed. Both outcomes are decided by a person, in the specification.

    Mock servers and parallel frontend work

    A mock server generated from the specification lets frontend and mobile developers build against the API before the NestJS code exists.

    • Examples drive the mock: each response returns the examples written in the specification.
    • Error paths: the mock can return documented errors on request, so clients build their error handling early.
    • Same source: when the specification changes, the mock and the generated client types change together.

    Keep the mock in the same pipeline as the tests. A mock that is regenerated by hand drifts as quickly as hand-written types.

    Where does AI help, and where must it not decide?

    AI helps with volume, turning each schema, status code and example into test cases faster than a person typing them. It must not decide what the API should do.

    • Good use: drafting tests for each documented response, including 400, 404 and 409 cases.
    • Good use: generating boundary values from schema constraints such as minLength, maximum and enum.
    • Good use: pointing out missing error responses for a reviewer to add to the specification.
    • Not its decision: inventing behaviour the specification does not describe.
    • Not its decision: changing an expected value so a failing test passes.

    Give the assistant the specification and the operation, not the implementation. Tests written from the code tend to confirm whatever the code already does, which defeats the point of writing them first.

    Generated types in a NestJS codebase

    Generated types keep controllers honest: when the specification changes a field, the TypeScript build breaks wherever the old shape is still used.

    • Folder: generate into a separate folder that nobody edits by hand.
    • CI: regenerate on every build, and fail if the committed output differs.
    • Validation: keep runtime request validation, because TypeScript types disappear at runtime.
    • Mapping: map generated types to domain objects at the controller edge, so business logic does not depend on wire formats.

    Some teams generate DTO classes with validation decorators, others validate requests against the JSON Schema directly. Either works if there is one source, the specification, and nothing is maintained twice.

    How should tests check responses against the contract?

    Tests should validate every response body against the schema in the specification, as well as asserting specific values. Schema validation catches the extra field or wrong type that a hand-written assertion skips.

    • Validate request and response bodies with a JSON Schema validator in API tests.
    • Assert status codes and content types exactly as the specification lists them.
    • Use the specification's examples as fixtures, so examples stay correct.
    • Fail any test that receives a status code the specification does not document.

    How does it differ from consumer-driven contract testing?

    Consumer-driven contract testing starts from what each consumer expects and checks the provider against those expectations. Contract-first design starts from one shared specification that all sides agree before building.

    Teams can use both. The specification-first workflow is simpler when one team owns the API and its main clients; consumer-driven contracts add value when many independent consumers depend on one provider.

    Handling breaking changes

    Breaking changes are handled in the specification before any code, with a diff tool in CI that flags removed fields, new required fields and changed types.

    • Flag: the pull request shows which operations change incompatibly.
    • Decide: version the path, add the field as optional, or agree a migration with consumers.
    • Deprecate: mark old operations as deprecated in the specification before removing them.

    What are the common mistakes with AI-driven TDD in NestJS?

    The common mistakes with AI-driven TDD in NestJS come from letting the model or the code quietly replace the specification as the source of truth.

    • Prompting from the implementation: AI tests confirm existing bugs.
    • Accepting AI tests unread: tests assert behaviour nobody agreed.
    • Hand-editing generated types: the next regeneration overwrites the fix, or the fix is never regenerated.
    • No drift check: decorators and the designed file slowly disagree.
    • Specification without examples: tests and mocks have nothing concrete to work from.

    What does it mean for your build plan?

    Contract-first testing moves effort earlier, into API design reviews, and adds a few pipeline steps.

    • Pick the code generator and the mock server, and agree where generated files live.
    • Add CI steps for regeneration, schema validation in tests, the drift check and the breaking-change diff.
    • Set a review rule for AI-drafted tests, with a named reviewer per pull request.
    • For an existing API, export the current specification, clean it up and make it the source from then on.
    • Choose one style guide for the specification, covering naming, error format and pagination.

    Expect the first few operations to take longer, while the team agrees conventions and tunes the prompts it gives the AI assistant. After that, most of the effort moves into design reviews, which is where it belongs.

    How can Agnotic help with contract-first NestJS testing?

    Agnotic sets up the OpenAPI workflow, code generation, mock servers, AI test drafting and the CI checks, and trains your team on the review gate, so tests stay tied to the contract rather than to the code.

    One specification, tests that follow it

    We set up contract-first testing for your NestJS services.

    Sources

    Frequently Asked Questions

    Engineering leaders and teams running NestJS backends with web or mobile clients, who want faster test writing and fewer mismatches between what the API promises and what it does.

    Talk to an engineer about your project

    Share your NestJS service layout and any existing OpenAPI document. We will propose the generator, pipeline checks and review gate.