How to Use should in Cypress for Assertions
In Cypress, use
should to make assertions about elements or values by chaining it after a command. It checks if the subject meets conditions like visibility, text content, or attributes, and fails the test if the assertion is false.Syntax
The should command is chained after a Cypress command that yields a subject, like an element or value. It takes a string describing the assertion or a callback function for custom checks.
Basic syntax:
cy.get(selector).should('assertion')- checks a built-in assertion on the element.cy.get(selector).should('assertion', value)- checks a built-in assertion with a value.cy.get(selector).should(callback)- runs a custom function with the element.
javascript
cy.get('button').should('be.visible') cy.get('input').should('have.value', 'Hello') cy.get('h1').should(($el) => { expect($el.text()).to.include('Welcome') })
Example
This example shows how to check if a button is visible and has the correct text using should. It also demonstrates a custom assertion with a callback.
javascript
describe('Using should in Cypress', () => { it('checks button visibility and text', () => { cy.visit('https://example.cypress.io') cy.get('button').should('be.visible') cy.get('button').should('contain.text', 'type') cy.get('button').should(($btn) => { expect($btn).to.have.length(1) expect($btn.text()).to.match(/type/i) }) }) })
Output
Test passes if the button is visible and contains the text 'type'; fails otherwise.
Common Pitfalls
Common mistakes when using should include:
- Using
shouldwithout chaining it to a Cypress command that yields a subject. - Passing incorrect assertion strings or wrong number of arguments.
- Not waiting for elements to appear before asserting, causing flaky tests.
- Using
thenwhenshouldis more appropriate for automatic retries.
Correct usage ensures Cypress retries the assertion until it passes or times out.
javascript
/* Wrong: should not be used alone */ // should('be.visible') // This will cause an error /* Right: chained to a command */ cy.get('button').should('be.visible')
Quick Reference
| Usage | Description |
|---|---|
| should('be.visible') | Asserts element is visible on the page |
| should('have.text', 'text') | Asserts element's exact text content |
| should('contain.text', 'partial') | Asserts element contains partial text |
| should('have.value', 'value') | Asserts input element's value |
| should(callback) | Runs custom assertion function with yielded subject |
Key Takeaways
Use
should chained after Cypress commands to assert element states or values.should automatically retries assertions until they pass or timeout, making tests stable.Pass assertion strings for common checks or a callback function for custom logic.
Avoid using
should without a preceding Cypress command that yields a subject.Use
should for assertions that need automatic retry; use then for one-time actions.