0
0
Cypresstesting~5 mins

Why assertions verify expected behavior in Cypress

Choose your learning style9 modes available
Introduction

Assertions check if the app works as we expect. They help catch mistakes early by comparing actual results to what should happen.

When you want to confirm a button is visible before clicking it.
When you need to check if a form shows an error message after wrong input.
When verifying that a page loads the correct title.
When ensuring a list contains the expected number of items.
When confirming a user is redirected to the right page after login.
Syntax
Cypress
cy.get('selector').should('assertion', expectedValue)

cy.get('selector') finds the element on the page.

.should() is where you check the expected behavior.

Examples
Check if the button is visible on the page.
Cypress
cy.get('button').should('be.visible')
Verify the input field contains the text 'hello'.
Cypress
cy.get('input').should('have.value', 'hello')
Assert that the current URL includes '/dashboard'.
Cypress
cy.url().should('include', '/dashboard')
Sample Program

This test opens the login page, enters wrong password, clicks submit, and checks if the error message appears with correct text.

Cypress
describe('Login Page Test', () => {
  it('shows error on wrong password', () => {
    cy.visit('https://example.com/login')
    cy.get('input[name="username"]').type('user1')
    cy.get('input[name="password"]').type('wrongpass')
    cy.get('button[type="submit"]').click()
    cy.get('.error-message').should('be.visible')
    cy.get('.error-message').should('contain.text', 'Invalid password')
  })
})
OutputSuccess
Important Notes

Assertions stop the test if they fail, so you know exactly where the problem is.

Use clear and simple assertions to make tests easy to understand.

Summary

Assertions confirm the app behaves as expected.

They help find bugs early by checking real results against expected ones.

In Cypress, use .should() with selectors to write assertions.