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

How to wait for two parallel XHR requests in Cypress

1个答案

1

When handling concurrent XHR requests in Cypress, we typically use Cypress's cy.intercept() method to intercept network requests and cy.wait() to wait for these requests to complete. Below are the detailed steps and an example:

Steps

  1. Define Requests: Use cy.intercept() to define the requests we want to intercept. Specify exact requests using methods, URLs, or other attributes.
  2. Alias Assignment: Assign unique aliases to these intercepted requests so they can be referenced in subsequent tests.
  3. Trigger Requests: Execute actions that initiate these requests, such as clicking buttons or submitting forms.
  4. Wait for Requests to Complete: Use cy.wait() with the assigned aliases to wait for one or more requests to finish.

Example

Suppose we have a page where clicking a button concurrently triggers two XHR requests: one to retrieve user information and another to retrieve the user's order details.

javascript
describe('Concurrent XHR Requests Test', () => { it('Should correctly wait for two concurrent XHR requests', () => { // Intercept the first XHR request cy.intercept('GET', '/api/users/*').as('getUser'); // Intercept the second XHR request cy.intercept('GET', '/api/orders/*').as('getOrders'); // Trigger XHR requests cy.visit('/some-page'); cy.get('#load-data').click(); // Assume this button triggers the above requests // Wait for both requests to complete cy.wait(['@getUser', '@getOrders']); // Perform assertions after the requests complete cy.get('@getUser').its('response.statusCode').should('eq', 200); cy.get('@getOrders').its('response.statusCode').should('eq', 200); }); });

In this example, we first set up two intercept calls to monitor GET requests for /api/users/* and /api/orders/*, assigning aliases getUser and getOrders respectively. After clicking the button, we use cy.wait() to wait for both requests to complete. Finally, we retrieve detailed request information using cy.get() and perform assertions to verify expected behavior.

With this approach, we can effectively manage and test multiple concurrent network requests in a page, ensuring they all respond correctly and align with test expectations.

2024年6月29日 12:07 回复

你的答案