In end-to-end testing with Cypress, asserting JSON responses from API endpoints is a common and critical operation. I'll demonstrate this with a practical example.
Suppose we want to test an API that returns user details. The returned JSON structure is approximately as follows:
json{ "id": 1, "name": "John Doe", "email": "john.doe@example.com", "roles": ["Admin", "User"] }
We need to verify that the returned data is accurate, including the user's id, name, email, and roles. Here are the steps to perform assertions using Cypress:
- Initiate API Request:
First, use the
cy.request()method to make a GET request.
javascriptcy.request('GET', '/api/users/1').as('userRequest');
- Assert Response Status Code: Confirm the request was successful; the status code should be 200.
javascriptcy.get('@userRequest').its('status').should('equal', 200);
- Assert Response Body: Next, validate the content of the response body.
javascriptcy.get('@userRequest').its('body').should('include', { id: 1, name: 'John Doe', email: 'john.doe@example.com' });
- Deeply Assert Arrays and Objects: Since the user's roles is an array, confirm it contains specific roles.
javascriptcy.get('@userRequest').its('body.roles').should('be.an', 'array').and('deep.eq', ['Admin', 'User']);
By doing this, we not only verify basic data types and structure but also deeply validate the exact content of complex types like arrays. Such assertions ensure API responses fully meet expectations, helping to improve application stability and user trust.