0
0
Cypresstesting~10 mins

Asserting response bodies in Cypress - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test sends a GET request to a sample API endpoint and verifies that the response body contains the expected data.

Test Code - Cypress
Cypress
describe('API Response Body Assertion', () => {
  it('should verify the response body contains expected user data', () => {
    cy.request('https://jsonplaceholder.typicode.com/users/1')
      .then((response) => {
        expect(response.status).to.equal(200);
        expect(response.body).to.have.property('id', 1);
        expect(response.body).to.have.property('username', 'Bret');
      });
  });
});
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsCypress test runner initialized-PASS
2Sends GET request to https://jsonplaceholder.typicode.com/users/1Request sent, waiting for response-PASS
3Receives response with status 200 and JSON bodyResponse received with user dataCheck response.status equals 200PASS
4Asserts response body has property 'id' with value 1Response body contains user objectresponse.body.id === 1PASS
5Asserts response body has property 'username' with value 'Bret'Response body contains user objectresponse.body.username === 'Bret'PASS
6Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: Response body does not contain the expected 'username' property with value 'Bret'
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the response status?
AIt checks that the status code is 500
BIt checks that the status code is 404
CIt checks that the status code is 200
DIt does not check the status code
Key Result
Always assert both the HTTP status code and key properties in the response body to ensure the API returns the expected data.