乐闻世界logo
搜索文章和话题

How to make assertion for below body request via Cypress?

1个答案

1

In Cypress, you can use its built-in commands to assert API requests and their response results. Typically, you send HTTP requests using cy.request() and receive the response. Then, leverage Cypress's assertion libraries (Chai, Mocha, and Sinon) to validate various aspects of the response, including status codes, response bodies, headers, and more.

Here are several steps and examples for asserting API request response results:

  1. Send Request: Use cy.request() to send a GET or POST request.
javascript
cy.request('GET', 'https://api.example.com/data') .then((response) => { // The response object contains all response information });
  1. Assert Status Code: Use .should() to verify the response status code.
javascript
cy.request('GET', 'https://api.example.com/data') .its('status') .should('equal', 200);
  1. Assert Response Body: Validate the returned JSON or other formatted data.
javascript
cy.request('GET', 'https://api.example.com/data') .its('body') .should('include', { key: 'value' });
  1. Assert Response Headers: Check response headers to ensure they contain the correct information.
javascript
cy.request('GET', 'https://api.example.com/data') .its('headers') .its('content-type') .should('include', 'application/json');
  1. Assert Response Time: Validate that the response time meets performance expectations.
javascript
cy.request('GET', 'https://api.example.com/data') .its('duration') .should('be.lessThan', 1000); // Assuming response time is less than 1000ms

Here is a more comprehensive example that combines these concepts:

javascript
describe('API Test with Cypress', () => { it('Validate the response of the API', () => { cy.request('GET', 'https://api.example.com/data') .then((response) => { // Assert status code is 200 expect(response.status).to.eq(200); // Assert returned data contains specific key-value pairs expect(response.body).to.have.property('key', 'value'); // Assert Content-Type header in response expect(response.headers).to.have.property('content-type', 'application/json'); // Assert response time is less than 1 second expect(response).to.have.property('duration').below(1000); }); }); });

This ensures your application's API behaves as expected during integration testing. It is crucial for validating the API's availability, correctness, and performance.

2024年6月29日 12:07 回复

你的答案