Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress - wait for xhr request which triggered by UI operation

Tags:

cypress

I have an app with select element, when changing the select value, the page makes an XHR request to load some data and insert it to a table. I want cypress to wait till the request end, and after the data rendered on the table, then to check the number of table rows.

this is the code I currently have:

    cy.get('[name="pageselct"]').select('300'); // fire a request to load data

    // the below line get executed before the data actually loaded: 
    const totalTableRows = cy.get('#listingsData > tr').length; 

how can I achieve it?

like image 886
Or Bachar Avatar asked Oct 29 '18 21:10

Or Bachar


People also ask

How do you handle XHR request in Cypress?

An object in XHR can request data from a server in the form of a response. Cypress can not only be used for front end automation, but also can control the network traffic by directly accessing the XHR objects. Then, it applies the assertions on the objects.It can mock or stub a response.

How do you wait for a particular element in Cypress?

Use timeout per command Sometimes, you simply want to wait until a certain element appears, but everything else on the page is pretty fast. For these cases, you can use the options object and change timeout for a certain command. Notice how we are adding the timeout into our . get() command, not the .

How do you wait for a request to finish before moving on with Cypress?

Then, right after logging into the application, I use cy. wait() , passing the alias created previously ( @getNotes ). That way, Cypress will wait for such a request to end before moving on to run the test that successfully creates a note.


1 Answers

Waiting for XHRs is easy in cypress. See https://docs.cypress.io/api/commands/wait.html#Alias for more info.

// Start the server that waits for routes
cy.server();

// Set the XHR up as a route, do not mock the return (unless you want to)
cy.route("GET", "/xhr/to/wait/for").as("getData");

// Fire a request to load data
cy.get('[name="pageselct"]').select('300');

// Wait for the route to complete
cy.wait("@getData");

// The below line will not get executed before the data actually loaded
const totalTableRows = cy.get('#listingsData > tr').length; 
like image 127
Brendan Avatar answered Sep 29 '22 13:09

Brendan