问题
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?
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()
回答1:
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.
回答2:
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 a 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.
来源:https://stackoverflow.com/questions/50685393/avoid-using-cy-wait-to-wait-for-a-page-to-load-due-to-aborted-get-request-cypr