0
0
CypressHow-ToBeginner ยท 3 min read

How to Use expect in Cypress for Assertions

In Cypress, use expect to write assertions that check if values meet your expectations. It works by passing the actual value to expect() and chaining matcher methods like .to.equal() to verify conditions.
๐Ÿ“

Syntax

The basic syntax of expect in Cypress is: expect(actual).matcher(expected). Here, actual is the value you want to test, and matcher is a method that checks if actual meets the condition defined by expected.

Common matcher methods include to.equal(), to.be.true, to.include(), and to.have.length().

javascript
expect(actualValue).to.equal(expectedValue)
expect(booleanValue).to.be.true
expect(array).to.include(item)
expect(string).to.have.length(length)
๐Ÿ’ป

Example

This example shows how to use expect to check if a number equals 10 and if a string contains a word.

javascript
describe('Using expect in Cypress', () => {
  it('checks number equality and string content', () => {
    const number = 10
    const text = 'Hello Cypress'

    expect(number).to.equal(10)
    expect(text).to.include('Cypress')
  })
})
Output
Test passes if number is 10 and text contains 'Cypress'.
โš ๏ธ

Common Pitfalls

One common mistake is mixing expect with Cypress commands that are asynchronous. expect works with values, not promises. Always resolve values before using expect.

Another pitfall is using incorrect matcher methods or forgetting to chain them properly.

javascript
/* Wrong: Using expect directly on a Cypress command (which returns a promise-like object) */
// expect(cy.get('button')).to.exist // This will not work

/* Right: Use .then() to get the actual element before asserting */
cy.get('button').then(($btn) => {
  expect($btn).to.exist
})
๐Ÿ“Š

Quick Reference

MatcherDescriptionExample
to.equal(value)Checks if actual equals expectedexpect(5).to.equal(5)
to.be.trueChecks if value is trueexpect(true).to.be.true
to.include(item)Checks if array or string includes itemexpect([1,2]).to.include(2)
to.have.length(n)Checks length of array or stringexpect('abc').to.have.length(3)
to.be.nullChecks if value is nullexpect(null).to.be.null
โœ…

Key Takeaways

Use expect(actual).matcher(expected) to write clear assertions in Cypress.
Always resolve Cypress commands before using expect to avoid async issues.
Common matchers include to.equal(), to.be.true, to.include(), and to.have.length().
Incorrect chaining or using expect on Cypress commands directly causes test failures.
Refer to matcher methods cheat-sheet for quick assertion writing.