Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid using cy.wait() to wait for a page to load due to aborted get request cypress

I'm running a cypress test that requires a page to load before clicking an element and logging in, but for some reason a failed (and aborted) GET request is causing the page to take forever to load and eventually it times out unless I add a cy.wait(6000) before the cy.click() call. I need to somehow wait for the page to load without using a cy.wait(). How can I do this, given that I cant fix the aborted GET request?

enter image description here

  cy.visit(loginUrl)
  cy.url().should('contain', '#/loginPortal')
  cy.wait(6000) //Allows page to load before trying to log in, needs to be removed
  cy.contains('ButtonText').click()
like image 480
ejscribner Avatar asked Jun 04 '18 16:06

ejscribner


People also ask

How do you avoid Cy wait 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.

What is Cy wait () in Cypress?

cy. wait() can time out waiting for the request to go out. cy. wait() can time out waiting for the response to return.

What command can be used to wait in Cypress?

To wait for a specific amount of time or resource to resolve, use the cy. wait() command.

How do you increase your Cypress wait time?

Request timeout The first cycle is waiting to respond to the request to close the browser, and the request timeout by default duration is 5000 milliseconds. This means that Cypress will wait up to 5 seconds before issuing a matching request when you start waiting for an alias request.


2 Answers

You can make Cypress wait for any specific XHR call, before you assert. How long it waits is defined by the responseTimeout configuration.

cy.server();
cy.route('**/api/getData').as('getData');
cy.visit('/home');
cy.wait('@getData');
cy.contains('ButtonText').click()

Cypress best practices: Unnecessary-Waiting.

Cypress docs on wait Alias.

like image 111
Rui Marques Avatar answered Oct 04 '22 10:10

Rui Marques


It's useful to tell Cypress to wait for a specific URL to be present in the address bar before continuing.

cy.get('#login').click();
cy.location('pathname', {timeout: 20000}).should('include', '/path/to/page');

This can be used to wait for redirects which are triggered after login or any page change. That may be a necessary first step before using cy.wait for an XHR request, as Rui Marques describes.

like image 25
emery Avatar answered Oct 04 '22 11:10

emery