OpenAPI as a source of tests
A test should read the OpenAPI specification rather than a pasted copy of it, so there are not two sources of truth. From the specification you take types for compilation, negative cases from required, schemas for validating responses, a linter and version comparison for breaking changes. Of these, only schema validation checks a real response, and the specification describes shape rather than business rules, so functional tests are still needed.
API · Contracts
The schema in the test was copied by hand and the spec changed. How can the test notice by itself?
The tests hold a copy of the transfer schema made six months ago. Since then the specification added a field and changed an enum, and the tests stay green because they check a stale copy. This is the classic "two sources of truth" problem. The fix: a test reads the specification, not its imprint.
The lesson covers what you can take from OpenAPI for automated tests: schemas, types, negative cases, a linter and version comparison.
How it works: the specification as raw material
The specification already holds what a test wants to know: which fields are required (required), which types and bounds apply, which codes an operation returns, which values are allowed. Instead of duplicating that in a test, you can read the file and derive checks from it. Then when the contract changes, everything changes at once: a test or a new version produces an error or forces a rebuild.
Four ways to use it (the example below takes another order: types and negative cases first, then the linter and version diff; schema validation is covered in the next lesson):
What the specification gives automated tests in CI
The first layer works on the file itself and knows nothing about the server, the fourth compares two files. Only the third checks that a response really matches the schema, and that is what finds drift between code and documentation.
Example: from a schema copy to a source of truth
The bad variant. The test checks the structure by hand:
const body = await res.json();
expect(body.id).toBeDefined();
expect(body.amount).toBeDefined(); // passes for "150" and for null
Such a test does not know that amount must be a number or that status must belong to a list. If the field disappears from the contract, the test stays the same.
Step one: types from the specification. A generator takes the file and creates TypeScript interfaces:
npx openapi-typescript openapi.yaml -o src/api.d.ts
import type { components } from './api';
type Transfer = components['schemas']['Transfer'];
test('created transfer is pending', async ({ request }) => {
const res = await request.post('/v1/transfers', { data: VALID });
const body = (await res.json()) as Transfer;
const expected: Transfer['status'] = 'pending'; // 'pendng' will not compile
expect(body.status).toBe(expected);
});
Now removing or renaming a field in the specification breaks the test build after regeneration instead of being caught at run time. Types work at compile time and do not replace checking the response, because res.json() still returns whatever the server sent.
Step two: negative cases from the request schema. Fields in required give a ready list of "without field X the request is rejected":
import { readFileSync } from 'node:fs';
import { parse } from 'yaml';
const spec = parse(readFileSync('openapi.yaml', 'utf8'));
const req = spec.components.schemas.TransferRequest;
const VALID = { toAccount: 'UA21...', amount: 150, currency: 'UAH' };
for (const field of req.required as string[]) {
test('missing ' + field + ' is rejected', async ({ request }) => {
const data: Record<string, unknown> = { ...VALID };
delete data[field];
const res = await request.post('/v1/transfers', { data });
expect(res.status()).toBe(400);
});
}
Add a required field to the specification and the case appears on its own. The expected code here comes from the documentation (400). The server from the previous lesson returns 422, and this test is what exposes the mismatch.
Steps three and four live in CI. A linter finds incomplete descriptions, and a comparison tool (oasdiff, for example) shows whether a PR contains a breaking change against the main branch:
npx @stoplight/spectral-cli lint openapi.yaml
oasdiff breaking origin-main.yaml openapi.yaml --fail-on ERR
Limits and alternatives
- A specification does not guarantee business logic. The schema says
amountis a number, not that the right sum was debited. Functional tests are needed for that. - Quality depends on the file. If the specification is generated from code and describes no errors, no negative cases come out of it. Then a linter rule "every operation has a 4xx" is more useful than anything else.
- Generating tests from scratch. Tools exist that produce fuzzing from OpenAPI (Schemathesis, for example). They quickly find a 500 on strange input, but they are not a substitute for thought-out test design: they do not know what is right for the business.
- A mock server from the specification lets the front end work before the back end is ready. It answers with the examples in the specification, so it goes stale together with it.
Typical mistakes
- Copying the schema into the test. A month later the copy drifts from the original and the test stops meaning anything.
- Generating types but not regenerating them in CI. Then they sit in the repository as one more copy.
- Validating only success responses. Errors have schemas too, and that is where drift is most common.
- Ignoring linter warnings. A missing 4xx description or a field without a type or
requiredis not cosmetic, it is a hole in the contract.
Check yourself
A required field currency was added to the request in the specification. Which automated tests should react without manual edits?
Answer
Negative cases generated from required (a "without currency" case appears) and the types, if regenerated: code that builds a request without the new field stops compiling.
Why do types from the specification not replace validating a response against a schema?
Answer
Types work at compile time and only describe expectations. res.json() returns what really arrived, so only a schema check at run time verifies the real response.
required and bounds, and I do not treat the specification as a replacement for functional tests, because it describes shape, not business rules.