ArticleZip > How To Wait For Element To Disappear In Cypress

How To Wait For Element To Disappear In Cypress

Cypress is a powerful testing framework that can make our lives easier when it comes to writing tests for our web applications. However, sometimes we encounter situations where we need to wait for an element to disappear before proceeding with our test. In this article, we will explore how to do just that using Cypress.

### Why Wait for an Element to Disappear?

Waiting for an element to disappear is a common scenario in UI testing. For example, you may want to wait for a loading spinner to disappear before interacting with other elements on the page or verify that an error message has been removed after a specific action.

### Using Cypress Commands

Cypress provides us with a set of powerful commands to interact with elements on the page. To wait for an element to disappear, we can use the `should` command along with a custom assertion.

Here's how you can wait for an element to disappear in Cypress:

1. **Select the Element**: First, you need to select the element you want to wait for. You can use a CSS selector or any other method supported by Cypress to select the element.

2. **Assertion**: Use the `should` command with a custom assertion to wait for the element to disappear.

Javascript

cy.get('selector-for-element').should('not.exist');

With this command, Cypress will wait for the element selected by `selector-for-element` to disappear from the DOM before proceeding with the test.

### Handling Timeout

By default, Cypress waits for commands and assertions to complete for up to 4 seconds before timing out. If the element does not disappear within this time frame, the test will fail with a timeout error. To adjust the timeout, you can use the `timeout` option:

Javascript

cy.get('selector-for-element').should('not.exist', { timeout: 10000 }); // Wait for up to 10 seconds

Adjust the timeout value according to your specific scenario to ensure that Cypress has enough time to wait for the element to disappear.

### Complete Example

Let's put it all together with a complete example:

Javascript

it('should wait for element to disappear', () => {
  cy.get('selector-for-element').should('not.exist');
  // Add assertions or interactions after the element disappears
});

In this example, Cypress will wait for the element specified by `selector-for-element` to disappear before executing any assertions or interactions inside the test.

### Conclusion

Waiting for an element to disappear in Cypress is a crucial feature when writing robust UI tests. By using the `should` command with a custom assertion, you can ensure that your tests are reliable and accurately reflect the behavior of your web application.

Next time you encounter a scenario where you need to wait for an element to disappear in Cypress, remember these simple steps to handle it efficiently and effectively. Happy testing!

×