QA Interview Hub · Knowledge base · Quizzes · Українська

Cypress › API testing

How do you validate a response schema?

A response is validated with a JSON Schema that describes the whole shape: required fields, types, formats, ranges and whether extra keys are allowed. The schema lives in a separate file; a validator such as ajv with allErrors: true returns all violations, since by default it stops at the first. additionalProperties: false catches leaks but breaks tests on a safe extension. A schema checks shape, not meaning, so values are checked separately.

Cypress · API testing

The backend quietly changed the price from a number to a string and the test is green. How do you check the whole structure instead of single fields?

Checking single fields catches only what you thought to ask about. A typical story: the backend removes a field the test did not check or turns a number into a string, and it is the front end that breaks, not the test. A JSON Schema describes the whole shape of a response: which fields are required, their types, formats and ranges, and whether extra keys are allowed. Checking the contract becomes one declaration instead of a dozen expect calls.

How it works and why

The schema is stored as a separate JSON file (in fixtures or next to the tests) and a validator compares a response body with it and returns a list of violations. Key words: required (mandatory fields), type, enum, minimum, format, additionalProperties. The last decides whether the test breaks on a new unknown field. Strictness is a choice: false quickly catches an accidental leak of extra data but breaks tests on every harmless extension of the response.

Fields one by one versus a schema

Single fields

Checked id and name

The backend removed currency and made price a string. The test stayed green because it asked nothing about them.

JSON Schema

The whole structure

required, types and formats are described once. A contract change fails the test at once with a clear message.

Figure 1. A schema catches changes the test did not think to ask about.

Example: a product schema and validation

A schema describing the expected shape of a product:

{
  "type": "object",
  "required": ["id", "name", "price", "currency"],
  "properties": {
    "id": { "type": "integer" },
    "name": { "type": "string", "minLength": 1 },
    "price": { "type": "number", "minimum": 0 },
    "currency": { "enum": ["UAH", "USD", "EUR"] }
  },
  "additionalProperties": false
}

Way one: ajv, the most common JSON Schema validator. A Cypress test runs in the browser, so the library can be imported straight into a spec or a support file, with no need for cy.task. The key point: expect(ok, message) with ajv.errorsText shows every violation, not just “expected false to be true”.

// cypress/support/schema.ts
import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv({ allErrors: true });
addFormats(ajv);

export function expectSchema(schema: object, data: unknown) {
  const validate = ajv.compile(schema);
  const ok = validate(data);
  // a message with every violation, not just “false”
  expect(ok, ajv.errorsText(validate.errors)).to.eq(true);
}

// test
import schema from '../fixtures/schemas/product.json';
import { expectSchema } from '../support/schema';

it('GET /products/42 matches the schema', () => {
  cy.request('/api/products/42').its('body').then((body) => {
    expectSchema(schema, body);
  });
});

Way two: the chai-json-schema plugin adds the be.jsonSchema assertion. It is simpler but runs on tv4, which is no longer maintained and knows only draft-04; for newer schema versions its README recommends chai-json-schema-ajv.

// plugin variant: cypress/support/e2e.ts
import chaiJsonSchema from 'chai-json-schema';
chai.use(chaiJsonSchema);

// test
cy.fixture('schemas/product.json').then((schema) => {
  cy.request('/api/products/42').its('body').should('be.jsonSchema', schema);
});

Limits and alternatives

A schema checks the shape, not the meaning. A response with the right types may hold a wrong amount or someone else’s record, so business values are checked with separate expect calls. A hand-written schema can drift from the real contract. It is more reliable to take it from the OpenAPI specification the backend team maintains: then the test catches a mismatch between the spec and the implementation. TypeScript projects have zod: a schema also describes the type, and schema.safeParse(body) returns errors. For contracts between teams there are consumer tests (Pact), but that is a separate topic. In Playwright no plugins are needed: the test runs in Node, so ajv is plugged in directly.

Typical mistakes

  • A schema with no required: vanished fields pass because only the type of present ones is checked.
  • Setting additionalProperties: false everywhere: a harmless extension of a response breaks dozens of tests.
  • Writing a schema “from the response” and never comparing it with the spec: the schema only repeats current behaviour.
  • Validating only the shape and checking no values.
  • Leaving expect(ok).to.eq(true) with no message: the report says “false” with no hint.

Check yourself

What does additionalProperties: false decide in a schema and when is it undesirable?

Answer

It forbids fields not in the schema, so the test fails on every new key. That is good for spotting accidental leaks, but undesirable when the response is often extended harmlessly: tests would break without need.

Why is schema validation not enough to call a response correct?

Answer

A schema checks the shape: types, presence, formats. Values can be wrong with correct types (a wrong amount, someone else’s record), so business checks are needed separately.

In an interview. Junior: Checking single fields misses changes I did not foresee, for example when the backend changed a type. So I validate the response against a JSON Schema and keep schemas in fixtures. Middle/Senior: I use ajv with a message about every violation, and prefer generating the schema from OpenAPI so the test catches a mismatch with the spec. I choose additionalProperties strictness deliberately and remember a schema checks the shape, so I check values separately.

More articles in this chapter