Assertions with .should() and expect()
You'll learn how to verify that your application's elements, content, and state match your expectations using Cypress's two assertion styles.
The Core Idea
After selecting elements with cy.get() or cy.contains(), you need to verify they're in the correct state. Cypress provides two ways to write assertions: the chainable .should() method (Cypress style) and the BDD expect() syntax (Chai style). Both check conditions like visibility, text content, attributes, and element properties.
Think of assertions as quality checks on an assembly line—you've grabbed a component, now you're inspecting it to ensure it meets specifications.
Using .should() for Chainable Assertions
The .should() method chains directly onto Cypress commands and reads naturally:
cy.get('[data-testid="welcome-message"]')
.should('be.visible')
.should('have.text', 'Welcome back, user!')
cy.get('input[name="email"]')
.should('have.value', 'test@example.com')
.should('have.attr', 'type', 'email')
You can also chain multiple conditions:
cy.get('button').should('be.visible').and('be.enabled')
Using expect() for Explicit Assertions
The expect() syntax requires yielding the element first but offers more flexibility:
cy.get('.status-badge').then($badge => {
expect($badge).to.have.class('active')
expect($badge.text()).to.equal('Online')
})
Key Takeaway: Use .should() for straightforward, chainable assertions on element visibility, text, attributes, and state—it auto-retries until conditions pass. Use expect() when you need more complex logic or multiple assertions on the same element without retrying between each check.