0
0
Cypresstesting~5 mins

expect() for BDD assertions in Cypress

Choose your learning style9 modes available
Introduction

We use expect() to check if something in our app works as we want. It helps us catch mistakes early.

To check if a button is visible on the page.
To verify if a text appears after clicking a link.
To confirm a number value is correct after a calculation.
To test if a list contains the expected items.
To make sure a form input has the right value.
Syntax
Cypress
expect(actualValue).to.be.expectedCondition(expectedValue)

actualValue is what you get from your app.

expectedCondition is what you want to check, like equal, contain, or be.visible.

Examples
Checks if the number 5 is equal to 5.
Cypress
expect(5).to.equal(5)
Checks if the string 'Hello' contains 'ell'.
Cypress
expect('Hello').to.contain('ell')
Checks if the value is true.
Cypress
expect(true).to.be.true
Checks if the button is visible on the page.
Cypress
cy.get('button').then(($button) => {
  expect($button).to.be.visible
})
Sample Program

This test opens a page and checks if the main heading text is exactly 'Kitchen Sink'.

Cypress
describe('My First Test', () => {
  it('checks if the heading is correct', () => {
    cy.visit('https://example.cypress.io')
    cy.get('h1').then(($heading) => {
      expect($heading.text()).to.equal('Kitchen Sink')
    })
  })
})
OutputSuccess
Important Notes

Always use expect() inside a test to make sure your app behaves as expected.

Use clear and simple conditions to keep tests easy to understand.

Remember that expect() works well with Cypress commands that return values.

Summary

expect() helps check if your app works right.

Use it to compare actual results with what you want.

It makes tests clear and easy to read.