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:
- Send Request: Use
cy.request()to send a GET or POST request.
javascriptcy.request('GET', 'https://api.example.com/data') .then((response) => { // The response object contains all response information });
- Assert Status Code: Use
.should()to verify the response status code.
javascriptcy.request('GET', 'https://api.example.com/data') .its('status') .should('equal', 200);
- Assert Response Body: Validate the returned JSON or other formatted data.
javascriptcy.request('GET', 'https://api.example.com/data') .its('body') .should('include', { key: 'value' });
- Assert Response Headers: Check response headers to ensure they contain the correct information.
javascriptcy.request('GET', 'https://api.example.com/data') .its('headers') .its('content-type') .should('include', 'application/json');
- Assert Response Time: Validate that the response time meets performance expectations.
javascriptcy.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:
javascriptdescribe('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 回复