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

How to get POST API response in Cypress?

1个答案

1

In Cypress, you can use its built-in command cy.request() to send HTTP requests, including GET, POST, PUT, and DELETE. When you need to get the response from a POST API, you can use the cy.request() command with the method set to POST. Here is an example:

javascript
// Initiate a POST request and obtain the response cy.request({ method: 'POST', url: 'https://your-api-endpoint.com/login', // Replace with the actual API endpoint body: { username: 'user1', // Pass the required request body parameters here password: 'pass123' } }).then((response) => { // Process the response data expect(response.status).to.eq(200); // Assert the response status code is 200 expect(response.body).to.have.property('token'); // Assert the response body contains the 'token' property // You can use the returned data for subsequent tests const authToken = response.body.token; // Example: Send another request using the obtained token cy.request({ method: 'GET', url: 'https://your-api-endpoint.com/user-data', headers: { 'Authorization': `Bearer ${authToken}` } }).then((userDataResponse) => { // Process the user data response }); });

In this example, we first send a POST request to a login API and assert in the callback function whether the response status code is 200 and whether the response body contains the token property. Then, we use the obtained token as authentication information to initiate a new GET request to retrieve user data.

In practical applications, you might also need to perform more detailed validation on the response body, such as checking whether the returned data structure is correct and whether the data content meets expectations. The benefit of using cy.request() is that you can quickly validate the API without opening a browser, which is very useful in CI/CD pipelines.

2024年6月29日 12:07 回复

你的答案