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

How to wait for a successful response in Cypress tests

1个答案

1

When using Cypress for automated testing, it is crucial to ensure that the application correctly waits for and handles API responses. Cypress offers several methods to handle API requests and responses, ensuring the stability and reliability of tests.

Using cy.wait() to Wait for Specific API Calls

Cypress allows us to intercept HTTP requests made by the application using cy.intercept(), and then wait for the response using the cy.wait() method. This is an effective approach to ensure that the API call completes and returns the expected response.

Example:

Suppose we have a user login feature where, after submitting the login form, the frontend sends a POST request to /login. We can write the test code as follows:

javascript
describe('Login Feature Test', () => { it('Successful Login', () => { // Intercept the login request cy.intercept('POST', '/login').as('loginRequest'); // Fill the login form and submit cy.visit('/login'); cy.get('input[name=username]').type('user'); cy.get('input[name=password]').type('password'); cy.get('form').submit(); // Wait for the login request to succeed cy.wait('@loginRequest').its('response.statusCode').should('eq', 200); // Check if redirected to the homepage cy.url().should('include', '/home'); }); });

In this example, we first intercept the POST request to /login using cy.intercept(), and name the interception with .as('loginRequest'). After submitting the form, we use cy.wait('@loginRequest') to wait for the request to complete and verify that the response status code is 200, confirming a successful login.

Using cy.request() to Directly Send Requests

In addition to intercepting requests initiated by the frontend, Cypress provides the cy.request() method, which allows us to directly send HTTP requests from the test. This can be used to ensure that backend APIs are available before performing UI tests.

Example:

javascript
describe('Direct API Test for Login Feature', () => { it('Login via API Request', () => { cy.request({ method: 'POST', url: '/login', body: { username: 'user', password: 'password' } }).then((response) => { expect(response.status).to.eq(200); expect(response.body).to.have.property('token'); }); }); });

In this example, we do not trigger the request through UI elements but directly use cy.request() to send a login request and check the returned status code and response body.

Summary

When using Cypress for API testing, cy.intercept() and cy.wait() are powerful tools combined to wait for and validate HTTP requests. Additionally, cy.request() provides a more direct way to test backend APIs. These methods help ensure that APIs respond correctly during tests, thereby improving the accuracy and reliability of tests.

2024年6月29日 12:07 回复

你的答案