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

Cypress › API testing

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.

More articles in this chapter