Bird
Raised Fist0
Cypresstesting~15 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. Which Cypress assertion checks if an element is present in the DOM, regardless of visibility?
easy
A. should('contain.text')
B. should('be.visible')
C. should('have.text')
D. should('exist')

Solution

  1. Step 1: Understand the meaning of exist assertion

    The exist assertion checks if the element is present in the DOM, even if it is hidden.
  2. Step 2: Compare with other assertions

    be.visible checks if the element is visible, have.text checks exact text content, and contain.text checks partial text. Only exist fits the question.
  3. Final Answer:

    should('exist') -> Option D
  4. Quick Check:

    Check presence = should('exist') [OK]
Hint: Exist means element is in DOM, visible or not [OK]
Common Mistakes:
  • Confusing 'exist' with 'be.visible'
  • Using 'have.text' to check presence
  • Thinking 'contain.text' checks existence
2. Which of the following is the correct Cypress syntax to assert that an element with id submitBtn is visible?
easy
A. cy.get('#submitBtn').should('exist')
B. cy.get('#submitBtn').should('contain', 'Submit')
C. cy.get('#submitBtn').should('be.visible')
D. cy.get('#submitBtn').should('have.text', 'Submit')

Solution

  1. Step 1: Identify the assertion for visibility

    The assertion should('be.visible') checks if the element is visible on the page.
  2. Step 2: Match syntax with element selector

    cy.get('#submitBtn') selects the element by id. Combining with should('be.visible') is correct syntax to check visibility.
  3. Final Answer:

    cy.get('#submitBtn').should('be.visible') -> Option C
  4. Quick Check:

    Visible check = should('be.visible') [OK]
Hint: Use should('be.visible') to check if element shows on page [OK]
Common Mistakes:
  • Using 'exist' instead of 'be.visible' for visibility
  • Confusing 'have.text' with visibility check
  • Using 'contain' without 'text' for exact text check
3. What will be the result of this Cypress test code?
cy.get('.message').should('have.text', 'Welcome!')

Assuming the element <div class='message'>Welcome!</div> is present and visible.
medium
A. Test passes because text matches exactly
B. Test fails because element is not checked for visibility
C. Test fails because 'have.text' is incorrect syntax
D. Test passes but ignores text content

Solution

  1. Step 1: Understand have.text assertion

    This assertion checks if the element's text content exactly matches the given string.
  2. Step 2: Check element and text

    The element <div class='message'>Welcome!</div> matches the text 'Welcome!' exactly, so the assertion passes.
  3. Final Answer:

    Test passes because text matches exactly -> Option A
  4. Quick Check:

    Exact text match = test passes [OK]
Hint: Exact text match means test passes with have.text [OK]
Common Mistakes:
  • Assuming visibility must be checked separately
  • Thinking 'have.text' is invalid syntax
  • Confusing 'have.text' with partial text check
4. Identify the error in this Cypress test code:
cy.get('.alert').should('be.visible').should('have.text', 'Error occurred')

Given the element <div class='alert' style='display:none'>Error occurred</div> is hidden.
medium
A. The element selector is incorrect
B. The element is hidden, so 'be.visible' assertion fails
C. 'have.text' assertion syntax is wrong
D. Chaining assertions is not allowed in Cypress

Solution

  1. Step 1: Check element visibility

    The element has style='display:none', so it is hidden and not visible.
  2. Step 2: Understand assertion failure

    The should('be.visible') assertion will fail because the element is hidden, causing the test to fail before checking text.
  3. Final Answer:

    The element is hidden, so 'be.visible' assertion fails -> Option B
  4. Quick Check:

    Hidden element fails 'be.visible' [OK]
Hint: Hidden elements fail 'be.visible' assertion [OK]
Common Mistakes:
  • Assuming 'have.text' runs even if visibility fails
  • Thinking chaining assertions is invalid
  • Ignoring element's CSS display property
5. You want to write a Cypress test to confirm a button with class .save-btn exists, is visible, and has the exact text Save. Which code snippet correctly performs all these checks?
hard
A. cy.get('.save-btn').should('exist').should('be.visible').should('have.text', 'Save')
B. cy.get('.save-btn').should('be.visible').should('contain.text', 'Save')
C. cy.get('.save-btn').should('exist').should('have.text', 'Save')
D. cy.get('.save-btn').should('have.text', 'Save').should('be.visible')

Solution

  1. Step 1: Check presence, visibility, and exact text

    We need to confirm the element exists, is visible, and has exact text 'Save'.
  2. Step 2: Verify chaining of assertions

    cy.get('.save-btn').should('exist').should('be.visible').should('have.text', 'Save') chains should('exist'), should('be.visible'), and should('have.text', 'Save') correctly to check all conditions.
  3. Final Answer:

    cy.get('.save-btn').should('exist').should('be.visible').should('have.text', 'Save') -> Option A
  4. Quick Check:

    Chain exist, visible, exact text for full check [OK]
Hint: Chain all assertions to check presence, visibility, and text [OK]
Common Mistakes:
  • Skipping 'exist' check before visibility
  • Using 'contain.text' instead of 'have.text' for exact match
  • Not chaining all required assertions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard