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

Cypress

API testing

cy.request from simple to Senior

What is cy.request and how does it differ from cy.intercept?

cy.request sends an HTTP request itself from the Cypress Node process, while cy.intercept only captures the requests the page makes. So cy.request is not subject to CORS or the same-origin policy, needs no open page, and cy.intercept cannot see it. Cookies from its response land in the browser, so a login through cy.request logs in the next cy.visit. It suits API tests and data setup.

Cypress · API testing

You need to create an order without the UI, but the test waits for a request nobody sends. Which command do you use?

Two colleagues write a test for placing an order. The first wants to prepare data quickly, so they set cy.intercept and wait for its alias, and the test times out: nothing was sent. The second wants to check that the “Place order” button sends the right body, and calls cy.request, which has nothing to do with the page. Both mixed up two commands that are similar only in that they touch HTTP.

How it works and why

cy.request does not run in the browser. The request goes from the Cypress Node process, so web-security rules do not apply: no CORS, no same-origin policy, and no page needs to be open. Cookies from the browser store for that URL are added to the request, and Set-Cookie from the response is saved in the browser. So a login through cy.request makes the next cy.visit logged in. The price of this independence: cy.intercept does not see such requests, and they are absent from the browser Network tab. They are visible only in the Command Log.

cy.intercept works the other way: it sends nothing itself, it only watches the requests the application makes and can modify them, replace the response or just count them. Where exactly the interception happens depends on the browser and the Cypress version, but for a test one thing matters: page traffic is intercepted, not cy.request calls.

Two HTTP commands, two different roles

cy.request

Sends a request itself

Runs from the Cypress Node process. No CORS, cookies are synced with the browser. For API tests, login and data setup.

cy.intercept

Sends nothing

Watches the requests the page makes and can replace the response. For mocks and checking what the front end sent.

Figure 1. These are not alternatives to each other but different tools: a request from the test versus watching the page’s requests.

Example: from confusion to the right choice

The wrong test waits for a request that does not exist:

// wrong: interception calls nothing, the alias never gets a hit
cy.intercept('POST', '/api/orders').as('create');
cy.wait('@create'); // waits for a request nobody makes

The right way is to split the roles: cy.request prepares data, and cy.intercept together with a UI action checks the front end:

// 1. cy.request SENDS the request itself and returns the response
cy.request('POST', '/api/orders', { items: [7] }).then((res) => {
  expect(res.status).to.eq(201);
});

// 2. cy.intercept WAITS for a request the page will make
cy.intercept('POST', '/api/orders').as('create');
cy.get('[data-cy=submit]').click();
cy.wait('@create').its('response.statusCode').should('eq', 201);

Now the first test checks the API itself (status, body, headers), and the second checks that the UI sent what it should and that the server answered as expected. They answer different questions, so neither command replaces the other.

Limits and alternatives

cy.request needs a URL: a relative path works with baseUrl set or after a cy.visit (Cypress then uses the visited page’s origin), otherwise write an absolute address. The response is returned whole, with no streaming. It cannot check what “the user sees” as a result of the request, the UI is for that. In Playwright the counterpart is the request fixture (APIRequestContext): no browser is started there either, so API tests are faster, and page.request shares cookies with the page.

Typical mistakes

  • Waiting for a cy.intercept alias for a request made by cy.request: nobody intercepts it.
  • Checking CORS through cy.request: it has none, so the check proves nothing.
  • Creating data through UI clicks when cy.request is enough: the test is longer and more fragile.
  • Testing only through cy.request and assuming the UI works too: the front end may send a different request.

Check yourself

A test makes a cy.request to /api/orders and then waits for cy.wait('@create') from an intercept on that URL. Why does this not work?

Answer

cy.request goes from the Node process, not from the page, so cy.intercept does not see it and the alias gets no request. The alias waits for a request the application will make.

Why does a login through cy.request make the next cy.visit logged in?

Answer

Cypress stores Set-Cookie from the response in the browser and the next page sends those cookies. That is how a cookie session works. A token in the response body does not behave like that, you pass it yourself.

In an interview. Junior: cy.request sends the request itself from the Node process, so CORS does not get in its way. I use it for API tests, login and data setup. cy.intercept sends nothing, it intercepts the page’s requests. Middle/Senior: I split the roles: cy.request for arranging and direct API checks, cy.intercept together with a UI action to check what the front end sent. I remember that intercept does not see cy.request, and that response cookies go straight into the browser.

How do you check the status, body and headers of a response?

cy.request yields status, body, headers and duration, so every part is checked. A body with Content-Type: application/json is already parsed, header names are lowercase, and content-type is compared with include because its value may carry a charset suffix. Keys and types of the body are checked, and the duration threshold is kept generous. Assertions after the request do not repeat it, so asynchronous states need bounded polling.

Cypress · API testing

The test checks only “status 200”, and the backend quietly changed the price type to a string. What else should the response have been checked for?

An API response has several parts and each breaks in its own way. The status says whether the request was accepted, headers describe the format and caching, the body carries data, and the response time shows whether speed degraded. A test that looks only at the status misses type drift, vanished fields and a wrong Content-Type. This lesson is about what exactly a test gets from cy.request and how to check it.

How it works and why

cy.request returns a response object: status, statusText, body, headers, duration, plus isOkStatusCode and requestHeaders. If the server answered with Content-Type: application/json, the body is already parsed into an object or array; for other types it is a string. Header names in headers are lower-case, so res.headers['content-type'], not Content-Type. The value often carries a suffix such as ; charset=utf-8, so compare with include, not eq.

What lies in a cy.request response

statuscode: exact, not “any 2xx”headerslower-case keys: content-typebodyJSON is already parsed into an objectdurationms; only a rough threshold
Figure 1. Four fields and what to check in each. Each breaks on its own.

There is an important detail about retries. The cy.request command is not repeated because of assertions or the response status: it is sent once (by default only network failures are retried, retryOnNetworkFailure). Only the following queries on the same value are retried: .its() and .should() re-read a field of the already stored response but do not ask the server again. If data has to “mature” (a queue, background processing), one cy.request cannot wait for it: you need your own polling loop.

Example: from “status 200” to a full check

A weak test checks only the code. A stronger one looks at all four parts:

cy.request('GET', '/api/products/42').then((res) => {
  expect(res.status).to.eq(200);
  expect(res.headers['content-type']).to.include('application/json');
  expect(res.body).to.have.property('id', 42);
  expect(res.body.price).to.be.a('number').and.be.greaterThan(0);
  expect(res.duration).to.be.lessThan(1000); // ms, a rough threshold
});

// one field: its() extracts, should() asserts
cy.request('/api/products/42').its('body.name').should('eq', 'Flask');
cy.request('/api/products').its('body').should('have.length.greaterThan', 0);

The difference shows when the backend changes: the weak test stays green when price becomes the string "450", while the strong one fails on a('number') with a clear message. Keep the duration threshold rough and generous: time is unstable on CI, and a test with a 200 ms limit will flake. Real speed requirements belong to load-testing tools.

For the response shape, checking keys and types is useful, not only single values:

cy.request('/api/products/42').then(({ body }) => {
  // the shape, not only values: keys and types the contract promises
  expect(body).to.have.all.keys('id', 'name', 'price', 'tags');
  expect(body.tags).to.be.an('array');
  expect(body).to.have.property('price').that.is.a('number');
});

all.keys fails both when a field vanished and when an extra one appeared. That is strict, so for responses that grow without harm use include.keys. A full structure check comes from schema validation (a separate lesson).

Limits and alternatives

Several expect calls in .then() stop at the first failure, so you will not see the rest until you fix it. For a JSON response with many fields, deep.include or a schema is handier. In Playwright a response is checked like this: await expect(res).toBeOK(), res.headers() and await res.json(); headers there are lower-case too.

Typical mistakes

  • Checking only the status: type, field and format changes slip through.
  • Writing headers['Content-Type'] with capitals: the value is undefined.
  • Comparing content-type with eq when a ; charset suffix exists: the test fails for no reason.
  • A hard duration limit: on CI the test becomes flaky.
  • Expecting cy.request to repeat itself until the data appears.

Check yourself

Why does res.headers['Content-Type'] return undefined although the header exists?

Answer

In Cypress response header names are lower-case, so you need res.headers['content-type']. Compare the value with include because it may carry ; charset=utf-8.

Will Cypress repeat cy.request itself if .its('body.status').should('eq', 'done') does not match?

Answer

No. The request is sent once and .its() and .should() only re-read the response already received. To wait for a state change you write your own polling: a recursive function with a new cy.request and a limit on attempts.

In an interview. Junior: cy.request returns the status, body, headers and duration. I take one field through its and make several checks in then: status, content-type, presence and type of fields, and a rough time threshold. Middle/Senior: I check every part of the response: the exact status, headers (lower case, include for content-type), the body shape with types, and I do not hang hard limits on duration. I remember assertions do not repeat the request, so for asynchronous states I write polling with a limit.

How do you test negative scenarios: 400, 401, 404?

By default cy.request fails on any status that is not 2xx or 3xx, so negative tests set failOnStatusCode: false. The expected code is then checked explicitly: 400 or 422 for invalid data, 401 without authentication, 403 without rights, 404 for a missing resource. Besides the code, the error body (no internal details) and the absence of side effects are checked. Without an expect on the status, the test passes on any response.

Cypress · API testing

A “401 without a token” test fails with a red 401, although that is exactly what it was meant to see. Where is the mistake?

A newcomer writes a negative test: a request with no token, expecting 401. They run it and Cypress shows red: cy.request() failed on … 401: Unauthorized (the full text is in Figure 2). The test was right in intent, but it failed on the command, before any check. This is one of the most common questions about cy.request, and behind it stands a default you have to know.

How it works and why

By default failOnStatusCode is true: any status that is not 2xx or 3xx counts as a failure of the command itself. The logic is clear: in a positive test a 500 response should fail the test at once, without a separate expect. But a negative test expects 4xx. So you set failOnStatusCode: false, and then a response of any status is handed to the test as a normal value. You then check the status yourself, and it is easy to forget: without an expect on the status the test passes on any response.

One request, two behaviours

Default

failOnStatusCode: true

A 400 or 404 response fails the test right on the command. Your expect never even runs.

For negative tests

failOnStatusCode: false

The response is handed to the test and you check the expected code, body and side effects yourself.

Figure 1. The option changes only who decides that a 4xx status is a failure: the command or your expect.

Reading the error: an expected 401 became a failure

1CypressError: cy.request() failed on:

http://localhost:3000/api/orders

The response we received from your web server was:

  > 2401: Unauthorized

This was considered a failure because the status code was not 2xx or 3xx.

3If you do not want status codes to cause failures pass the option: failOnStatusCode: false
  1. What: the cy.request command itself failed. Execution never reached your expect on the status.
  2. Status: 401, exactly what the negative test was meant to see. Cypress treats any status other than 2xx or 3xx as a failure.
  3. Hint: the message names the option that changes this rule.

What to do

Add failOnStatusCode: false and check the status explicitly: .its('status').should('eq', 401). Without that check the test passes on any response.

Figure 2. The real error text: the numbers lead to the explanations.

Example: three negative cases

Each case is a separate test with a clear expected code:

const noFail = { failOnStatusCode: false };

it('400: an empty order', () => {
  cy.request({ method: 'POST', url: '/api/orders', body: { items: [] }, ...noFail })
    .then((res) => {
      expect(res.status).to.eq(400);
      expect(res.body.message).to.contain('items');
    });
});

it('401: no token', () => {
  cy.request({ url: '/api/orders', ...noFail })
    .its('status').should('eq', 401);
});

it('404: a missing resource', () => {
  cy.request({ url: '/api/products/999999', ...noFail })
    .its('status').should('eq', 404);
});

Checking only the status is not enough. A negative request must be safe, so note two things. First: the error body. It must be clear and carry no internals (a stack trace, SQL). Second: side effects. A failed creation must not leave a record, and that is visible only by reading again:

it('400 does not create an order', () => {
  cy.request('/api/orders').its('body.length').then((before) => {
    cy.request({
      method: 'POST', url: '/api/orders', body: { items: [] },
      failOnStatusCode: false,
    }).its('status').should('eq', 400);

    // the negative request changed nothing
    cy.request('/api/orders').its('body.length').should('eq', before);
  });
});

it('302 without following the redirect', () => {
  cy.request({ url: '/old', followRedirect: false })
    .its('headers.location').should('eq', '/new');
});

The second example shows one more option: followRedirect: false stops the automatic jump, so you can check the 302 response itself and the Location header. Typical expectations: 400 or 422 for invalid data (the team should pick one and stick to it), 401 without authentication, 403 without rights, 404 for a missing resource, 409 for a conflict.

Limits and alternatives

There is a neighbouring option, retryOnStatusCodeFailure: when it is on, Cypress repeats the request after a status failure (off by default). Negative tests do not need it. Do not mix the two ideas: failOnStatusCode: false leaves the response to the test, while retryOnStatusCodeFailure repeats the request. In Playwright the behaviour is the opposite: request.get() does not fail on 4xx and 5xx, you check the status yourself with res.status() or toBeOK(); and the failOnStatusCode: true option turns on failing, as in Cypress.

Typical mistakes

  • Forgetting failOnStatusCode: false: the test fails on the command before expect.
  • Setting false and not checking the status: the test passes on any response, even 200.
  • Checking only the code and skipping the error body and side effects.
  • Mixing up 401 and 403: the first means “not authenticated”, the second “authenticated but without rights”.
  • Setting failOnStatusCode: false everywhere “just in case”: positive tests lose their fast failure.

Check yourself

A test with failOnStatusCode: false on a request meant to return 404 passes, but there is no expect on the status anywhere. Why is that a problem?

Answer

Without the option the command would fail on 4xx itself, and now it fails on no status at all. If the status is not checked, the test passes on 200 and on 500, so it proves nothing.

Besides the status, what else is worth checking in a negative creation test?

Answer

The error body (a clear message with no internals) and the absence of side effects: a repeated read must show that no record was created.

In an interview. Junior: By default cy.request fails on 4xx and 5xx. For negative cases I set failOnStatusCode false and check the expected code myself: 400 for invalid data, 401 without a token, 404 for a missing resource. Middle/Senior: Besides the code I look at the error body (a stable format, no internals) and at the fact that the negative request changed nothing in the state. I do not set false everywhere, so positive tests fail fast on server errors. In Playwright the default is the opposite: I check the status myself.

How do you build a CRUD chain in one test?

A CRUD chain in one test checks the whole life cycle of a resource: create, read, update, delete and a 404 afterwards. The id from the response travels on through .then(), and every step has its own expectation. If the chain fails midway, leftovers stay in the database, so state is cleaned before the test, data is made unique, and details go into separate tests with creation in beforeEach.

Cypress · API testing

A test creates a product, updates it and deletes it, then fails on step five. What is now left in the database and how do you clean it up?

A CRUD chain in one test checks the whole life cycle of a resource: creation, reading, updating, deletion and that the deleted resource is really gone. It resembles a miniature user scenario and catches mistakes single checks do not see, for example “DELETE returned 204 but the record stayed”. It has a price, though: the longer the chain, the harder it is to see where it broke, and the harder it is to clean up if it fell in the middle.

How it works and why

All Cypress commands are queued and run one after another, and a value travels from one step to the next through .then(): the callback receives the response, the id is taken from it and goes into the following requests. Each step has its own expectation: 201 on creation, 200 on reading and updating, 204 on deletion, 404 after it. The last check matters most: without it a deletion that did nothing would go unnoticed.

The life cycle of a resource in one test

POST /products201, take the id from the responseGET /products/id200, data matches what was sentPUT /products/id200, the new price in the responseDELETE /products/id204, no bodyGET /products/id404: the record is really gone
Figure 1. Each step has its own expectation; the last GET proves the DELETE worked.

Example: from a nested chain to a reliable one

The direct version, everything in one test:

it('product lifecycle', () => {
  cy.request('POST', '/api/products', { name: 'Flask', price: 500 })
    .then(({ status, body }) => {
      expect(status).to.eq(201);
      const url = '/api/products/' + body.id;

      cy.request(url).its('body.name').should('eq', 'Flask');

      cy.request('PUT', url, { name: 'Flask', price: 450 })
        .its('body.price').should('eq', 450);

      cy.request('DELETE', url).its('status').should('eq', 204);

      cy.request({ url, failOnStatusCode: false })
        .its('status').should('eq', 404);
    });
});

It is compact but has a weak spot: if the PUT step fails, the DELETE does not run and the “Flask” product stays in the database. The next run may fail on a duplicate. So there are two ways to make it more reliable. First: clean the state before the test (find and delete leftovers), as the Cypress documentation advises, and not only after. Second: split the chain into separate tests where creation goes in beforeEach and the id is held in an alias:

// the same lifecycle, but flat: the id lives in an alias
beforeEach(() => {
  cy.request('POST', '/api/products', { name: 'Flask', price: 500 })
    .its('body.id').as('id');
});

it('an update changes the price', function () {
  cy.request('PUT', '/api/products/' + this.id, { name: 'Flask', price: 450 })
    .its('body.price').should('eq', 450);
});

afterEach(function () {
  cy.request({ method: 'DELETE', url: '/api/products/' + this.id, failOnStatusCode: false });
});

The alias this.id works only in a regular function (function () {}), not in an arrow, and is reset between tests, so we create it in beforeEach. The clean life cycle is still worth keeping as one short test (a resource smoke), with the details split into separate cases: one failing leaves the others giving their own diagnosis.

Limits and alternatives

Some changes become visible not at once: queues, search indexes, caches. One cy.request is not enough for such a state, because the request is not repeated. Here you need polling with a limit on attempts:

// polling: the request is repeated until the state matches or attempts run out
const waitForStatus = (id: number, want: string, tries = 10): void => {
  cy.request('/api/jobs/' + id).then(({ body }) => {
    if (body.status === want) return;
    expect(tries, 'attempts left').to.be.greaterThan(0);
    cy.wait(500); // a deliberate pause between polls, not “to make it pass”
    waitForStatus(id, want, tries - 1);
  });
};

This is an exception, not a habit: the pause between attempts is deliberate and bounded, not “let us wait, maybe it passes”. In Playwright the same chain reads top to bottom without nested callbacks: const res = await request.post(...), const { id } = await res.json(). And for polling there is expect.poll.

Typical mistakes

  • A long chain with no cleanup: it fell in the middle and rubbish stayed in the database.
  • Not checking that the resource is really unavailable after DELETE (404).
  • Sending only the changed field in PUT when the API expects the full object: that is PATCH.
  • Using this.id in an arrow function: the value is empty.
  • Relying on test order: each test creates its own data.

Check yourself

Why does the end of a CRUD chain need one more GET that expects 404?

Answer

A 204 from DELETE says only that the server accepted the request, not that the record vanished. Reading again with a 404 proves the deletion really worked.

The test failed on the PUT step and the product stayed in the database. How do you make later runs survive that?

Answer

Clean the state before the test (delete leftovers before creating) and not rely only on a deletion step at the end. Also give each test unique data.

In an interview. Junior: I create an entity with POST, take the id from the response and pass it on through then. Then I read, update, delete and finally check that GET returns 404. Middle/Senior: One short test for the life cycle, with details in separate tests creating in beforeEach. I clean state before the test, not only after, make data unique, and for asynchronous states write polling with a limit instead of long pauses.

How do you organise authorisation in API tests?

API test login goes into one command, and credentials come from environment variables, not from code. In a token scheme the test passes the token itself in the Authorization header, while in a cookie scheme cy.request stores Set-Cookie in the browser and sends it with later requests. The password is hidden with log: false, and the result is cached with cy.session. Besides 200, 401 and 403 are checked.

Cypress · API testing

A test user’s password sits in the spec and shows up in the CI video. How do you organise login in API tests properly?

Most APIs need authentication, so the same block appears in every test: login, token, header. If you copy it, changing the login endpoint breaks dozens of files, and a password in code lands in the repository. So login goes into one command, credentials come from environment variables, and what to pass on (a token or a cookie) depends on how the server works.

How it works and why

There are two typical mechanisms. In a token scheme login returns a JWT or another token in the body, and the client sends it in an Authorization: Bearer … header. Cypress remembers nothing, so the test passes the token by hand. In a cookie scheme the server answers with Set-Cookie and cy.request saves it in the browser and adds it to later requests. No header is needed then, and cy.visit gets a logged-in user at once. To avoid logging in in every test, the result is cached through cy.session (a separate lesson).

Two authentication schemes

Token in a header

Authorization: Bearer …

Login returns the token in the body. The test puts it into every request itself. Cypress remembers nothing.

Cookie session

Set-Cookie

cy.request saves the cookie in the browser and sends it on by itself, including to cy.visit. No header needed.

Figure 1. Both are legitimate: the test must know which one the server uses and not invent a header it does not read.

Example: a custom command and three access scenarios

The command reads credentials through cy.env() (Cypress.env() was removed in Cypress 16) and returns the token. The log: false option hides the request with the password from the Command Log:

// cypress/support/commands.ts
Cypress.Commands.add('apiLogin', (role = 'USER') => {
  return cy
    .env([role + '_EMAIL', role + '_PASSWORD'])
    .then((creds) =>
      cy.request({
        method: 'POST',
        url: '/api/auth/login',
        body: { email: creds[role + '_EMAIL'], password: creds[role + '_PASSWORD'] },
        log: false, // the password stays out of the Command Log and the video
      }),
    )
    .its('body.token');
});

// cypress/support/index.d.ts
declare global {
  namespace Cypress {
    interface Chainable {
      apiLogin(role?: string): Chainable<string>;
    }
  }
}
export {};

Now the tests. For a token in a header Cypress has a handy auth: { bearer } option. Besides the positive scenario we check what breaks most often: a damaged token and a role without rights.

describe('API: orders', () => {
  let token: string;
  before(() => {
    cy.apiLogin().then((t) => { token = t; });
  });

  it('200 with a token', () => {
    cy.request({ url: '/api/orders', auth: { bearer: token } })
      .its('status').should('eq', 200);
  });

  it('401 with a damaged token', () => {
    cy.request({ url: '/api/orders', auth: { bearer: token + 'x' }, failOnStatusCode: false })
      .its('status').should('eq', 401);
  });

  it('403 for a role without rights', () => {
    cy.apiLogin('GUEST').then((guest) => {
      cy.request({ url: '/api/admin', auth: { bearer: guest }, failOnStatusCode: false })
        .its('status').should('eq', 403);
    });
  });
});

The token is received once in before and kept in a module variable, not in Cypress variables. The three cases check different things: 200 proves access works, 401 that the server really validates the token, 403 that access levels differ. A test that checks only 200 will not notice broken authorisation.

Limits and alternatives

Credentials do not belong in code or the repository: in CI they come from secrets, locally from uncommitted files. A separate user per role is easier to maintain than one “admin for everything”. A token has a lifetime, so a long suite may hit an expired token: for such cases there is a re-login before the run or a lifetime check. Under OAuth or SSO a direct login by request is sometimes impossible, and then a test-only sign-in is agreed. In Playwright such a context is created once through playwright.request.newContext with extraHTTPHeaders and handed out through a fixture.

Typical mistakes

  • A password in code or in a committed cypress.config: it lands in the repository.
  • Logging in in every test instead of once: extra requests and a slow suite.
  • Checking only 200 and not 401 and 403.
  • Putting a token into a header when the server uses cookies: the test passes by accident.
  • Leaving log: true on the request with a password: it ends up in the Command Log and the video.

Check yourself

How does passing authorisation differ in a token scheme and a cookie scheme in Cypress?

Answer

The test puts a token into a header itself, for example through auth: { bearer }. cy.request saves a cookie in the browser and adds it to later requests automatically.

Besides 200 for a logged-in user, which two negative access scenarios are worth checking?

Answer

401 with no token or a damaged token (the server checks authentication) and 403 for a user without the needed role (the server distinguishes rights).

In an interview. Junior: I log in by request, take the token and send it in Authorization. The logic is in an apiLogin command, and credentials come from environment variables, so they never reach the repository. Middle/Senior: I tell token and cookie schemes apart and do not mix them. I type the command, hide the password with log: false, and use a separate user per role. Besides 200 I check 401 and 403 and cache the login result through cy.session.

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.

How do you combine API and UI in one test?

State is prepared through the API and checked through the UI: cy.request creates data in milliseconds, while clicks are slow and unstable. When saved state matters, it is verified through the API again. Leftovers are cleaned at the start of the test, not only in afterEach, and cy.intercept is set before the action. At least one end-to-end test still goes fully through the UI, because API setup bypasses the form.

Cypress · API testing

A test creates a product through three screens of clicks just to check one row in the catalogue. Why is it slow and how do you shorten it?

A typical UI test is 80% preparation: register a user, create a product, add it to the cart. All of it is clicks that are slow, unstable and prove nothing about the feature under test. API requests prepare the same state in milliseconds. So the strong approach is: setup through the API, checking through the UI, and when you need to be sure of what was stored, checking through the API again.

How it works and why

All Cypress commands go through one queue, so cy.request and cy.visit sit calmly in beforeEach one after another. A cookie session from an API login immediately works for the UI (see the authorisation lesson). For the reverse direction, “what the front end sent”, you need a cy.intercept with an alias set before the action. The two commands complement each other: cy.request sends a request itself, cy.intercept watches what the page does.

The split of roles between API and UI

1. API: setupfast, no clicks, a known state2. UI: what we testone user action, not the whole path3. API or intercept: confirmationwhat went to the server and what was stored
Figure 1. The API is best at preparing and confirming, the UI tests what the user sees.

Example: setup through the API

Cleanup goes at the start, not in afterEach: the Cypress documentation advises cleaning state before tests, because a failed run or a closed browser will not execute the “after” code. First we delete leftovers, then create what is needed:

describe('catalog', () => {
  beforeEach(() => {
    // remove leftovers BEFORE the test: a failed run may have left them
    cy.request('/api/products?name=' + encodeURIComponent('Test product'))
      .its('body').each((p: { id: number }) => {
        cy.request('DELETE', '/api/products/' + p.id);
      });

    cy.request('POST', '/api/products', { name: 'Test product', price: 99 });
  });

  it('the product is visible in the catalogue', () => {
    cy.visit('/catalog');
    cy.contains('[data-cy=product]', 'Test product').should('be.visible');
  });
});

After that the test does one thing: it looks at the UI. If it fails, the cause is in the catalogue, not in “could not create a product through the form”.

The second technique works the other way: an action in the UI, and the check through the network and the API:

it('the form sends the right request and stores the product', () => {
  cy.intercept('POST', '/api/products').as('create');

  cy.visit('/admin/products/new');
  cy.get('[data-cy=name]').type('Flask');
  cy.get('[data-cy=price]').type('500');
  cy.get('[data-cy=save]').click();

  // 1. what the front end sent and what the server answered
  cy.wait('@create').then(({ request, response }) => {
    expect(request.body).to.deep.include({ name: 'Flask', price: 500 });
    expect(response?.statusCode).to.eq(201);

    // 2. what is really stored: an independent read through the API
    cy.request('/api/products/' + response?.body.id)
      .its('body.price').should('eq', 500);
  });
});

There are two levels of proof here: the intercepted request shows what the form sent, and an independent read through cy.request proves the data was stored, not merely accepted. If a test checks only “a green toast appeared”, a backend that stored nothing goes unnoticed.

Limits and alternatives

Setup through the API does not cancel a real UI test: at least one end-to-end test must walk the path as a user does, because API setup bypasses exactly what can break in a form. Test data must be unique or cleaned before the run, otherwise parallel runs fight over one record. Writing straight into the database from the test (through cy.task) is faster but bypasses the API’s business rules. In Playwright the same approach is packaged as a fixture: creation before await use(), deletion after, and the fixture is added to the signature of the test that needs it.

Typical mistakes

  • Creating data by clicks when a request can prepare it.
  • Cleaning only in afterEach: a failed run leaves rubbish that breaks the next one.
  • Setting cy.intercept after the click: the request has already gone and the interception misses it.
  • Waiting for a cy.intercept alias on a request made by cy.request: it does not see it.
  • Checking only a toast in the UI and not reading the stored state.

Check yourself

Why is it better to clean test data before the test and not only in afterEach?

Answer

The “after” code may not run: the run failed, the process was killed, the browser closed. The leftovers then break the next run. Cleaning at the start guarantees a clean start.

How do you check in one test both the front end’s request and that data was really stored?

Answer

Set a cy.intercept with an alias before the action, after the action wait with cy.wait('@alias') and check the request and response bodies, then independently read the resource through cy.request.

In an interview. Junior: I create test data through the API in beforeEach, and the test itself checks only the UI. This is much faster and more stable than creating everything by clicks. Middle/Senior: I keep setup in the API, one action in the UI and confirmation from the stored state. I clean leftovers at the start, not only in afterEach, and set the intercept before the action. I leave at least one end-to-end test fully through the UI.

What limits does Cypress have for API testing and when should you take another tool?

Cypress was built for UI tests, so even a pure API test starts a browser and runs slower than a plain HTTP client in Node. Cross-machine parallelism is built in only through Cypress Cloud, load comes from a single browser process, and there is no built-in WebSocket command. For a large standalone API suite, Playwright request, Postman with Newman or Supertest fit better, and k6, Gatling or JMeter for load.

Cypress · API testing

A team has three hundred API tests in Cypress and wants parallelisation and load testing. Is it the same tool?

Cypress was created as a tool for UI tests, and cy.request appeared as a helper. In time full API suites grew out of it, and it matters to know where that fits and where the tool works against itself. The question “when to take another tool” checks that you understand trade-offs, not only syntax.

How it works and why

The limits follow from the design. Cypress runs tests in a built-in browser, so even a pure API test starts a browser and runs in its environment: this is slower than a plain HTTP client in Node. Parallel runs across machines are built into Cypress Cloud (the --parallel --record flags); without it, specs have to be split between CI jobs by hand or with a plugin; the details are in the parallelisation lesson. Load comes from one browser process, not thousands of virtual users, so k6, Gatling and JMeter exist for that. WebSocket has no built-in command, and cy.intercept does not show its frames.

Where Cypress for APIs fits

Cypress is enough

The API serves UI tests

Data setup, login, checking what was stored after a UI action, a few direct checks. One stack, one team.

Better another tool

A separate API suite, load

Hundreds of standalone API tests, load scenarios, WebSocket, contract tests between teams.

Figure 1. The fork is not about the tool’s quality but about the role of API tests in the project.

Example: WebSocket through Node

There is no built-in command for WebSocket, but cy.task runs in Node, where the ws library exists. This is a working workaround, and also a signal: if such logic becomes the main one, a tool where it is native is handier.

// WebSocket in Cypress: no built-in command, so go through Node
// cypress.config.ts
import WebSocket from 'ws';

setupNodeEvents(on) {
  on('task', {
    wsEcho(msg: string) {
      return new Promise((resolve, reject) => {
        const ws = new WebSocket('ws://localhost:8080');
        ws.on('open', () => ws.send(msg));
        ws.on('message', (m) => { ws.close(); resolve(m.toString()); });
        ws.on('error', reject);
      });
    },
  });
}

// test
cy.task('wsEcho', 'ping').should('eq', 'ping');

Request bodies, by contrast, are not a problem: the form option gives application/x-www-form-urlencoded, and a FormData body is sent as multipart/form-data, so a file upload needs no plugin. The friction is elsewhere: every such test still starts a browser.

Limits and alternatives

  • Postman/Newman: collections handy for manual exploration and running in CI, good for testers without code.
  • Playwright request: no browser, parallel through workers, an HTML report. WebSocket can be listened to through page.on('websocket') or mocked through routeWebSocket.
  • Supertest, REST Assured: tests next to the backend code, in its language.
  • k6, JMeter, Gatling: load. Neither Cypress nor Playwright is meant for it.

For a more convenient display of requests in the Command Log there is the cypress-plugin-api plugin (check Cypress 16 compatibility). It changes the display, not the limits of the tool itself.

Typical mistakes

  • Keeping hundreds of standalone API tests in Cypress, paying for a browser they do not need.
  • Trying to load the system with a cy.request loop: that is not a load test.
  • Taking another tool “because it is trendy” when API tests only prepare data for the UI.
  • Assuming cy.intercept will check WebSocket.

Check yourself

Why is load testing not done with a cy.request loop?

Answer

The requests go from one process inside a test, with no load distribution, user models or percentile metrics. k6, JMeter and Gatling exist for that.

In which case is Cypress for API tests fully justified?

Answer

When API tests mostly serve UI tests (data setup, login, confirming what was stored) and the team wants one stack.

In an interview. Junior: Cypress is fine for API tests, but without Cloud there is no built-in parallelisation across machines, WebSocket is not tested directly, you cannot check load with it, and even for an API a browser starts. For many standalone API tests I take Postman with Newman or Playwright request. Middle/Senior: I look at the role of API tests: when they serve the UI suite I keep Cypress and one stack; when it is a separate large suite I move to a tool without a browser and with parallelisation. I give load to k6 or Gatling and keep contracts between teams separate.