Test Overview
This test uses the API-first setup pattern to create a user via API before visiting the UI page. It verifies that the user appears correctly on the page after setup.
This test uses the API-first setup pattern to create a user via API before visiting the UI page. It verifies that the user appears correctly on the page after setup.
describe('API-first setup pattern test', () => { it('creates user via API then verifies UI', () => { // Step 1: Create user via API cy.request('POST', '/api/users', { name: 'Alice', email: 'alice@example.com' }) .then((response) => { expect(response.status).to.eq(201); expect(response.body).to.have.property('id'); const userId = response.body.id; // Step 2: Visit user page cy.visit(`/users/${userId}`); // Step 3: Verify user name on page cy.get('[data-cy=user-name]').should('contain.text', 'Alice'); }); }); });
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Send POST request to /api/users with user data {name: 'Alice', email: 'alice@example.com'} | API server receives request and creates new user with unique ID | Response status is 201 Created and response body contains user ID | PASS |
| 2 | Visit the URL /users/{userId} where userId is from API response | Browser loads user detail page for the created user | — | PASS |
| 3 | Find element with data-cy attribute 'user-name' and check it contains text 'Alice' | User detail page shows user name 'Alice' in the specified element | Element text contains 'Alice' | PASS |
API-first setup pattern in Cypress tests?cy.request() to make HTTP requests.cy.request('POST', url, body) is the correct syntax.cy.request('POST', '/api/users', {name: 'Alice'}).then((response) => {
expect(response.status).to.eq(201)
cy.visit('/users/' + response.body.id)
})response.status to equal 201.expect(response.status).to.eq(201) fails and test stops with failure.cy.request('POST', '/api/items', {name: 'Book'})
.then((res) => {
expect(res.status).to.eq(200)
cy.wrap(res.body.id).as('itemId')
})
cy.get('@itemId').then((id) => {
cy.visit(`/items/${id}`)
})cy.get('@itemId') is called immediately, before the alias is set inside the then callback, causing undefined error.cy.get('@itemId') runs before the alias is set. -> Option Aconst users = [
{name: 'Anna'},
{name: 'Ben'},
{name: 'Cara'}
]
// Which code snippet is correct?cy.request are asynchronous and queued. To wait for all requests, use cy.wrap().each() with a .then() callback.forEach and for-of options place cy.visit() inside the loop, causing visits after each request instead of after all. The cy.wrap(users).each(...)
cy.visit() executes visit before requests due to queuing. Only cy.wrap(users).each(...).then(() => cy.visit()) waits for all requests before visiting.Pass the test and this pattern moves unknown