How to Assert Element Visible in Cypress: Simple Guide
In Cypress, you can assert that an element is visible using
cy.get(selector).should('be.visible'). This command checks if the element exists in the DOM and is visible to the user.Syntax
The basic syntax to assert visibility in Cypress is:
cy.get(selector): Finds the element using a CSS selector..should('be.visible'): Asserts that the element is visible on the page.
javascript
cy.get('selector').should('be.visible')
Example
This example demonstrates how to check if a button with the ID submit-btn is visible on the page.
javascript
describe('Visibility Test', () => { it('checks if submit button is visible', () => { cy.visit('https://example.cypress.io') cy.get('#submit-btn').should('be.visible') }) })
Output
Test passes if the element with ID 'submit-btn' is visible; fails otherwise.
Common Pitfalls
Common mistakes when asserting visibility include:
- Using incorrect selectors that do not match any element, causing the test to fail.
- Trying to assert visibility on elements that are hidden by CSS or not yet rendered.
- Confusing
be.visiblewithexist;existonly checks presence in DOM, not visibility.
javascript
/* Wrong: selector does not exist */ cy.get('#wrong-id').should('be.visible') /* Right: correct selector and visibility check */ cy.get('#submit-btn').should('be.visible')
Quick Reference
| Command | Description |
|---|---|
| cy.get('selector') | Selects element(s) by CSS selector |
| should('be.visible') | Asserts element is visible on the page |
| should('exist') | Asserts element exists in the DOM (may be hidden) |
| should('not.be.visible') | Asserts element is hidden or not visible |
Key Takeaways
Use cy.get(selector).should('be.visible') to assert element visibility in Cypress.
Ensure your selector matches the element you want to test to avoid false failures.
Remember that 'be.visible' checks if the element is visible, not just present in the DOM.
Check for CSS or rendering issues if visibility assertions fail unexpectedly.
Use the Quick Reference table to remember common visibility-related commands.