0
0
Cypresstesting~15 mins

cy.wait() for explicit waiting in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify explicit wait using cy.wait() before checking element visibility
Preconditions (2)
Step 1: Open the URL 'https://example.com/delayed-message'
Step 2: Click the button with id 'show-message-btn'
Step 3: Wait explicitly for 3 seconds using cy.wait()
Step 4: Verify that the element with id 'delayed-message' is visible and contains text 'Hello after wait!'
✅ Expected Result: After clicking the button and waiting explicitly, the delayed message appears and is visible with correct text
Automation Requirements - Cypress
Assertions Needed:
Verify element with id 'delayed-message' is visible
Verify element text equals 'Hello after wait!'
Best Practices:
Use cy.wait() only when necessary for explicit waiting
Use cy.get() with proper selectors
Use assertions with .should() for visibility and text
Avoid arbitrary waits longer than needed
Automated Solution
Cypress
describe('Explicit wait test with cy.wait()', () => {
  it('Waits explicitly before checking delayed message', () => {
    cy.visit('https://example.com/delayed-message');
    cy.get('#show-message-btn').click();
    cy.wait(3000); // wait for 3 seconds explicitly
    cy.get('#delayed-message')
      .should('be.visible')
      .and('have.text', 'Hello after wait!');
  });
});

This test opens the page, clicks the button to trigger a delayed message, then uses cy.wait(3000) to pause the test for 3 seconds explicitly. After waiting, it checks that the message element is visible and contains the expected text. Using cy.wait() here simulates waiting for an asynchronous event that takes time to complete.

We use cy.get() with id selectors for clarity and reliability. Assertions use .should() chaining to verify visibility and text content. This approach ensures the test waits exactly as needed before checking the result.

Common Mistakes - 3 Pitfalls
Using cy.wait() with too long or arbitrary time without reason
Not using cy.get() with proper selectors before assertions
{'mistake': 'Using cy.wait() instead of waiting for element visibility', 'why_bad': 'Waiting fixed time may fail if element appears sooner or later, causing flaky tests', 'correct_approach': "Prefer commands like cy.get().should('be.visible') which wait automatically for elements"}
Bonus Challenge

Now add data-driven testing with 3 different wait times: 1000ms, 2000ms, and 3000ms, verifying the message appears correctly each time

Show Hint