Cypress: Assertions
- Radek Stolarczyk
- Jul 13
- 1 min read
Updated: Jul 31
Assertions are an essential part of Cypress testing. They allow you to verify that elements exist, are in the correct state, and hold the expected data. Cypress provides powerful, built-in commands for making these assertions using .should()and .and().
What Is an Assertion?
An assertion checks that your application behaves the way it should. It can verify visibility, content, length, values, CSS properties, classes, and more.
Real-World Example: Asserting a Datepicker Input
This test case interacts with a datepicker component and validates that a selected date appears in the input field.
Key Points:
cy.wrap() allows you to use Cypress commands on a raw DOM element.
.invoke('prop', 'value') retrieves the current value from the input.
.should('contain', value) is used for partial match.
.should('have.value', value) is used for an exact match.
Common Cypress Assertion Patterns
1. Check if Element Exists and is Visible
2. Text Contains Specific Content
3. Check Element’s Exact Value
4. Check Length of a List or Table
5. Check CSS Style or Class
Best Practices for Cypress Assertions
Use .should() and .and() directly after Cypress commands whenever possible.
Use .then() only when you need to perform custom logic or chain non-Cypress code.
Prefer .should('have.value') over .invoke() for straightforward input value assertions.
Keep assertions simple and readable — avoid overcomplicating your checks.