🚫STOP using cy.wait()! Use timeout or aliases instead. Cypres IO.

_config.yml

When writing tests, I often encounter a delay in the appearance of elements on the frontend page. This can be due to waiting for a request with data that the rendering of elements on the page depends on, or other conditions. The easiest way to wait for an item to appear is to use the:

1
cy.wait(time)

But with this option, we are waiting until the end for the specified time, even if the element has already appeared on the page.

1
2
3
cy.visit('https://www.demoblaze.com')
cy.wait(5_000)
cy.get('#search').type('Peter Pan')

You can say that we can change the default timeout of Cypress. (By default, Cypress waits 4 seconds to retrieve and verify items.)

_config.yml

1
2
3
4
5
6
7
8
9
10
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  // These settings apply everywhere unless overridden
  defaultCommandTimeout: 5000,
  // Command timeout overridden for E2E tests
  e2e: {
    defaultCommandTimeout: 10000,
  },
})

But this is not the right solution for waiting on elements. My suggestion is to use dynamic timeout for elements instead of hardcoded wait value. When the element is found, the timeout will be interrupted even if the time we set has not expired yet.

1
cy.get('#search', { timeout: 10_000 })

Now the dynamic timeout works for each element on a per-element basis! It is also possible to wait for the response needed to render the page.

1
2
3
cy.intercept('GET', '/books').as('getBooks')
cy.wait('@getBooks')
cy.get('#search').type('Peter Pan')

Thanks to everyone who read this article to the end, I hope you found it useful.

Sources used in the article:

https://docs.cypress.io/api/commands/wait

Get new posts and extra comments

You'll get every new post with extra unpublished, subscriber-only comments!

No ads, no spam. Just notifications when I do cool stuff. Unsubscribe at any time.