Open In App

How to Wait for element Attribute to Change in Cypress?

Last Updated : 24 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cypress is a popular end-to-end testing framework that allows you to write fast, easy, and reliable tests for your web applications. One common scenario in web testing is waiting for an element's attribute to change before performing an action. In this article, we will explore how to wait for an element attribute to change in Cypress.

Example

Let's consider a simple example where we have a button with a disabled attribute that changes to enabled after a certain condition is met. We want to wait for the button's disabled attribute to change to false before clicking on it.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Wait for Attribute Change</title>
</head>
<body>
  <button id="myButton" disabled>Click me</button>

  <script>
    setTimeout(() => {
      document.getElementById('myButton').disabled = false;
    }, 2000);
  </script>
</body>
</html>

In our Cypress test, we can use the should() command to wait for the button's disabled attribute to change to false.

Cypress Test Code

JavaScript
// cypress/integration/wait-for-attribute-change.spec.js
describe('Wait for attribute change', () => {
  it('waits for button to be enabled', () => {
    cy.visit('index.html')
    cy.get('#myButton').should('not.have.attr', 'disabled')
      .click()
      .should('have.text', 'Click me')
  })
})

In the above code, cy.get('#myButton') retrieves the button element, and should('not.have.attr', 'disabled') waits for the button's disabled attribute to change to false.

Terminal Output

When we run the test, Cypress will wait for the button's disabled attribute to change to false before clicking on it. The terminal output will look like this:

allcookies2
Output

Conclusion

Waiting for an element attribute to change is a common scenario in web testing. Cypress provides a simple and intuitive way to achieve this using the should() command. By using should('not.have.attr', 'attributeName'), we can wait for an element's attribute to change to a specific value before performing an action. This makes our tests more reliable and efficient.


Next Article

Similar Reads