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
| Matcher | Description | Example |
|---|---|---|
| to.equal(value) | Checks if actual equals expected | expect(5).to.equal(5) |
| to.be.true | Checks if value is true | expect(true).to.be.true |
| to.include(item) | Checks if array or string includes item | expect([1,2]).to.include(2) |
| to.have.length(n) | Checks length of array or string | expect('abc').to.have.length(3) |
| to.be.null | Checks if value is null | expect(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.