Should vs Expect in Cypress: Key Differences and Usage
should is a Cypress command used for chaining assertions directly on elements, while expect is a standalone assertion from Chai used for general JavaScript values. Use should for element state checks and expect for flexible value assertions.Quick Comparison
Here is a quick comparison of should and expect in Cypress highlighting their main differences.
| Factor | should | expect |
|---|---|---|
| Type | Cypress command chained on elements | Standalone Chai assertion function |
| Usage Context | Used on Cypress element queries (e.g., cy.get()) | Used for any JavaScript value or expression |
| Syntax Style | Chainable, asynchronous friendly | Synchronous, direct assertion |
| Automatic Retry | Yes, retries until assertion passes or timeout | No retry, immediate check |
| Common Use Case | Check element states like visibility, text, attributes | Check variables, function results, or values |
| Example | cy.get('button').should('be.visible') | expect(value).to.equal(5) |
Key Differences
should is a Cypress-specific command designed to be chained after element selectors like cy.get(). It automatically retries the assertion until it passes or times out, which helps handle dynamic page states. This makes should ideal for checking UI elements' properties such as visibility, text content, or CSS classes.
On the other hand, expect comes from the Chai assertion library integrated into Cypress. It is a standalone function used to assert any JavaScript value, not just elements. It performs immediate checks without retries, so it is best for static values or results from functions.
In summary, use should when you want Cypress to wait and retry assertions on elements, and use expect for direct, one-time checks on variables or expressions.
Code Comparison
cy.get('button').should('be.visible').and('contain.text', 'Submit')
Expect Equivalent
cy.get('button').then(($btn) => { expect($btn).to.be.visible expect($btn).to.contain.text('Submit') })
When to Use Which
Choose should when you want Cypress to automatically retry assertions on elements until they meet the condition, which is helpful for dynamic or slow-loading UI.
Choose expect when you need to assert values or results that do not require retries, such as variables, API responses, or immediate checks inside callbacks.
Using should improves test stability for UI checks, while expect offers flexibility for general assertions.
Key Takeaways
should is for chaining assertions on elements with automatic retries.expect is a standalone assertion for immediate checks on any value.should for UI element state validations that may change over time.expect for static value checks or inside callbacks.