Cypress expect Assertion Not Retrying Fix
In this tutorial, you'll learn about Cypress expect Assertion Not Retrying Fix. We cover key concepts, practical examples, and best practices.
Your expect() assertion inside a .then() callback fails intermittently — it works sometimes but not others because the DOM hasn't updated yet.
The Problem
// WRONG — expect() doesn't retry
cy.get('button').click();
cy.get('.result').then(($el) => {
expect($el.text()).to.equal('Success');
// If the text updates after a delay, this fails
});
expect() runs once. If the result text hasn't updated yet, the assertion fails even though it would pass after a short wait.
Step-by-Step Fix
1. Use should() for retry-able assertions
// RIGHT — should() retries until pass
cy.get('button').click();
cy.get('.result').should('have.text', 'Success');
2. Use expect() in .should() callbacks
// RIGHT — expect() inside should() callback
cy.get('.items li').should(($items) => {
expect($items).to.have.length(3);
expect($items.first()).to.contain('First');
});
3. Use expect() for non-DOM values
// RIGHT — expect() for static data
cy.request('/api/user').then((response) => {
expect(response.status).to.equal(200);
expect(response.body).to.have.property('name');
});
4. Use should() with multiple expect() calls
// RIGHT — multiple expectations with retry
cy.get('.user-profile').should(($profile) => {
expect($profile).to.be.visible;
expect($profile.find('.name')).to.contain('Alice');
expect($profile.find('.role')).to.contain('Admin');
});
Expected output:
✓ retry-able text assertion
✓ chained assertions
✓ API response validation
Prevention Tips
- Use
should()for DOM element assertions (retry enabled) - Use
expect()insideshould(callback)for complex checks - Use
expect()for API responses (already resolved) - Use
expect()for static/computed values - Remember:
expect()is immediate,should()retries
Common Mistakes with assert expect
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world CYPRESS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro