Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Wait until page is fully loaded

I'm using Cypress to test my spa. Sometimes the page displays quickly and sometimes it is very slow. I need to be able to check for a button or text that will display once the page is loaded, but do not want to wait for eternity.

I've been using excessively long wait periods but would like the test to run faster.

let targeturl = 'http:\\something.com'
let longwait = 2500

describe('Update Case', () => {
  it('Create Case', () => {   
    cy.visit(targeturl)
    cy.wait(longwait)
    cy.get('button').contains('Create').click()

I want to be able to set a wait that waits until the button 'Create' is displayed.

like image 315
Kathrine Stallings Avatar asked Jul 10 '19 14:07

Kathrine Stallings


1 Answers

By default, Cypress will wait for your page to load all resources before continuing the test. Your cy.wait() shouldn't be necessary. The default timeout for cy.visit() is 60 seconds.

Also, cy.get() will retry finding your element until the element exists. The default timeout is 4 seconds, but you can increase it.

Something like this is generally all you need:

describe('Update Case', () => {
  it('Create Case', () => {   
    cy.visit(targeturl)
    cy.get('button').contains('Create').click()

If you find that this isn't working, perhaps because your page takes more than 4 seconds to render after it loads all resources, then you can do something like this:

describe('Update Case', () => {
  it('Create Case', () => {   
    cy.visit(targeturl)
    // wait up to 30 seconds for some element to exist before continuing the test
    cy.get('.some-element-in-your-app-that-only-exists-once-page-has-loaded', { timeout: 30000 })
    cy.get('button').contains('Create').click()

In general, you shouldn't ever need to use cy.wait() to delay your tests by a certain number of milliseconds. Doing so is almost always a bad practice.

like image 160
Zach Bloomquist Avatar answered Oct 21 '22 05:10

Zach Bloomquist