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?
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.
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 .
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With