0
0
Cypresstesting~15 mins

Common assertions (exist, be.visible, have.text) in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - Common assertions (exist, be.visible, have.text)
What is it?
Common assertions in Cypress are checks that confirm if elements on a web page meet certain conditions. For example, 'exist' checks if an element is present in the page's code, 'be.visible' confirms if the element is actually shown to the user, and 'have.text' verifies the exact text inside an element. These assertions help testers ensure the web page behaves as expected.
Why it matters
Without these assertions, testers would not know if the web page elements are correctly loaded, visible, or displaying the right content. This could lead to broken features or bad user experiences going unnoticed. Assertions catch problems early, saving time and improving software quality.
Where it fits
Before learning assertions, you should understand basic Cypress commands to select elements. After mastering assertions, you can learn advanced testing techniques like custom assertions, chaining, and handling asynchronous behavior.
Mental Model
Core Idea
Assertions are like checkpoints that confirm if a web page element exists, is visible, and shows the correct text during testing.
Think of it like...
Imagine checking a package delivery: you first confirm the package exists at your door (exist), then you check if you can see it clearly (be.visible), and finally you open it to verify the contents inside (have.text).
┌───────────────┐
│ Select Element │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│   Assert      │
│ ┌───────────┐ │
│ │ exist     │ │
│ │ be.visible│ │
│ │ have.text │ │
│ └───────────┘ │
└───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding element existence
🤔
Concept: Learn how to check if an element is present in the page's HTML.
In Cypress, use cy.get(selector).should('exist') to verify the element is in the DOM. For example, cy.get('#login-button').should('exist') checks if the login button is present.
Result
The test passes if the element is found; it fails if the element is missing.
Knowing how to confirm element existence prevents tests from running on missing elements, which would cause errors.
2
FoundationChecking element visibility
🤔
Concept: Learn to verify if an element is visible to the user on the page.
Use cy.get(selector).should('be.visible') to check if the element is shown and not hidden by CSS or off-screen. For example, cy.get('.menu').should('be.visible') ensures the menu is visible.
Result
The test passes if the element is visible; it fails if hidden or not rendered.
Visibility checks ensure users can actually see and interact with elements, not just that they exist in code.
3
IntermediateVerifying element text content
🤔
Concept: Learn to assert that an element contains specific text.
Use cy.get(selector).should('have.text', 'expected text') to check exact text. For example, cy.get('h1').should('have.text', 'Welcome') confirms the heading text.
Result
The test passes if the element's text matches exactly; it fails otherwise.
Text assertions confirm the content shown to users is correct, catching content errors early.
4
IntermediateCombining multiple assertions
🤔Before reading on: do you think you can chain multiple assertions on one element in Cypress? Commit to yes or no.
Concept: Learn how to check multiple conditions on the same element in one command chain.
Cypress allows chaining assertions like cy.get(selector).should('exist').and('be.visible').and('have.text', 'Hello'). This runs all checks sequentially on the element.
Result
The test passes only if all assertions succeed; it fails if any fail.
Chaining assertions makes tests concise and efficient, reducing repeated element lookups.
5
AdvancedHandling dynamic content with assertions
🤔Before reading on: do you think assertions immediately check the element state or wait for it to appear? Commit to your answer.
Concept: Understand Cypress's automatic waiting for elements and assertions to pass before failing.
Cypress retries commands and assertions for a default timeout (usually 4 seconds). For example, cy.get('.alert').should('be.visible') waits until the alert appears visible or times out.
Result
Tests become more stable by waiting for dynamic changes instead of failing immediately.
Knowing Cypress's retry behavior helps write reliable tests for pages with delayed or animated content.
6
ExpertCustom assertions and error messages
🤔Before reading on: do you think Cypress allows creating your own assertion logic? Commit to yes or no.
Concept: Learn how to write custom assertions for complex checks and improve test feedback.
Use .should(callback) with a function to write custom logic. For example: cy.get('.item').should($el => { expect($el.text().trim()).to.match(/^Item \d+$/) }) You can also customize error messages for clarity.
Result
Tests can verify complex conditions beyond built-in assertions and provide clearer failure reasons.
Custom assertions empower testers to handle unique scenarios and improve debugging efficiency.
Under the Hood
Cypress commands queue actions and assertions, running them asynchronously in the browser. Assertions like 'exist' check the DOM presence, 'be.visible' checks CSS properties and layout to confirm visibility, and 'have.text' reads the element's text content. Cypress automatically retries commands and assertions until they pass or timeout, handling dynamic page changes smoothly.
Why designed this way?
Cypress was designed to simplify end-to-end testing by providing automatic waiting and clear assertions. This avoids flaky tests caused by timing issues common in web testing. The built-in assertions cover common needs, while allowing custom logic for flexibility.
┌───────────────┐
│ Test Script   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Command Queue │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Browser DOM   │
│ & CSS Engine  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Assertion     │
│ Evaluation    │
│ (exist,      │
│ be.visible,  │
│ have.text)   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 'exist' guarantee the element is visible to the user? Commit yes or no.
Common Belief:If an element exists, it must be visible to the user.
Tap to reveal reality
Reality:'exist' only means the element is in the page code; it can be hidden or off-screen.
Why it matters:Assuming existence means visibility can cause tests to pass even when users cannot see or interact with elements.
Quick: Does 'have.text' check partial text or exact text by default? Commit your answer.
Common Belief:'have.text' checks if the element contains the expected text anywhere inside.
Tap to reveal reality
Reality:'have.text' checks for exact text match, including whitespace and case.
Why it matters:Misunderstanding this leads to false test failures or passing tests that miss subtle text errors.
Quick: Does Cypress immediately fail an assertion if the element is not found? Commit yes or no.
Common Belief:Cypress fails assertions immediately if the element is missing or condition not met.
Tap to reveal reality
Reality:Cypress retries commands and assertions for a timeout period before failing, allowing for dynamic content loading.
Why it matters:Not knowing this can cause confusion about test timing and lead to unnecessary waits or flaky tests.
Quick: Can you chain multiple assertions on one element in Cypress? Commit yes or no.
Common Belief:You must write separate commands for each assertion on an element.
Tap to reveal reality
Reality:Cypress supports chaining multiple assertions on the same element in one command chain.
Why it matters:Failing to use chaining leads to verbose, less efficient tests and repeated element lookups.
Expert Zone
1
Assertions like 'be.visible' check multiple CSS properties including display, visibility, opacity, and element size, not just presence.
2
Cypress's automatic retry applies to both commands and assertions, but custom assertions inside .should(callback) must handle retries manually if needed.
3
Using 'have.text' is sensitive to whitespace and exact text; for partial or case-insensitive checks, use 'contain.text' or custom assertions.
When NOT to use
Avoid relying solely on 'exist' or 'be.visible' for complex UI states like animations or transitions; use Cypress's .wait() or custom event listeners instead. For text checks needing partial matches or ignoring case, prefer 'contain.text' or regex-based custom assertions.
Production Patterns
In real projects, testers combine these assertions with retries and timeouts to handle slow-loading elements. They also write custom assertions for accessibility checks or dynamic content validation. Chaining assertions reduces flakiness and improves test readability.
Connections
Event-driven programming
builds-on
Understanding how Cypress waits and retries assertions relates to event-driven programming where code reacts to changes or events asynchronously.
Quality control in manufacturing
same pattern
Assertions in testing are like quality checks on a production line, ensuring each product (web element) meets standards before moving forward.
Human perception psychology
builds-on
The difference between 'exist' and 'be.visible' mirrors how humans perceive objects: something can exist but not be noticed if hidden, highlighting the importance of visibility in user experience.
Common Pitfalls
#1Checking only element existence without visibility
Wrong approach:cy.get('#submit').should('exist')
Correct approach:cy.get('#submit').should('exist').and('be.visible')
Root cause:Assuming presence in the DOM means the element is usable by the user.
#2Using 'have.text' expecting partial match
Wrong approach:cy.get('.message').should('have.text', 'Success')
Correct approach:cy.get('.message').should('contain.text', 'Success')
Root cause:Misunderstanding that 'have.text' requires exact text match.
#3Not accounting for dynamic loading causing flaky tests
Wrong approach:cy.get('.loading').should('not.exist') cy.get('.content').should('be.visible')
Correct approach:cy.get('.content', { timeout: 10000 }).should('be.visible')
Root cause:Expecting elements to appear instantly without waiting or retries.
Key Takeaways
Assertions in Cypress confirm if elements exist, are visible, and contain correct text, ensuring web pages behave as expected.
The 'exist' assertion checks for presence in the page code, but does not guarantee visibility to users.
'be.visible' verifies that elements are actually shown and interactable, which is crucial for user experience.
'have.text' requires exact text matching; for partial matches, use 'contain.text' or custom assertions.
Cypress automatically retries assertions to handle dynamic content, making tests more reliable and less flaky.