In frontend automation testing with Cypress, waiting and verifying XHR requests is a common need. Cypress offers multiple approaches for handling network requests, with the most frequently used being the cy.intercept() method to intercept and manage XHR requests. I will explain how to use this method to wait for XHR requests and provide a concrete example.
Step 1: Intercept Requests
In your test, you should first intercept the XHR request of interest. The cy.intercept() method enables you to monitor and manipulate network requests and responses. You can specify the request method and URL, and Cypress will intercept it when the request is made.
javascript// Intercept GET request cy.intercept('GET', 'https://example.com/api/data').as('getData');
Step 2: Trigger the Request
Next, you need to trigger this request within the application. This is commonly achieved by simulating user interactions, such as clicking a button or submitting a form.
javascript// Trigger the XHR request operation, e.g., clicking a load button cy.get('button.load').click();
Step 3: Wait for Request Completion
Once the request is triggered, you can use the cy.wait() method to wait for the request to complete. You can reference the alias defined in cy.intercept() to wait for the specific request.
javascript// Wait for request completion cy.wait('@getData').its('response.statusCode').should('eq', 200);
Here, cy.wait('@getData') will pause the test execution until the request named 'getData' is completed. You can further inspect the response, as illustrated in the example, to verify that the response status code is 200.
Example
Suppose you are testing a user information page that fetches data from https://example.com/api/users after the user clicks the 'Load User Information' button. The test script might be written as follows:
javascriptdescribe('User Information Page', () => { it('should load and display user information', () => { // Visit the user information page cy.visit('/user-info'); // Intercept API request cy.intercept('GET', 'https://example.com/api/users').as('loadUser'); // Simulate user click operation cy.get('button#load-user-info').click(); // Wait for XHR request completion cy.wait('@loadUser').then((interception) => { expect(interception.response.statusCode).to.eq(200); expect(interception.response.body).to.have.property('name'); }); // Verify information on the page cy.get('#user-name').should('contain', 'John Doe'); }); });
This example illustrates how to wait for and verify XHR requests in Cypress. By following these three steps—intercepting requests, triggering requests, and waiting for requests to complete—you can ensure your tests cover all aspects of network interactions.