Cypress 07 ๐ฒ Assertions โ should, expect, and Retry-ability
Cypress has two assertion styles that look similar and behave differently. cy.get(...).should(...) is the chainable assertion that retries until it passes or the timeout expires. expect(...) is the Mocha/Chai assertion that runs once at the moment it is called. The first is the one that makes a test resilient to a page that loads asynchronously; the second is the one that fails if the value is not ready. The distinction is the same as Playwright’s web-first versus value assertions, and it is the most common source of flaky Cypress tests.
This chapter covers the should chainable assertion, the expect assertion and its place inside .then(), and the retry model that makes should the default choice for anything that reads from the DOM. The sections that follow walk through the assertion forms, the retry behavior, and the cases where expect is the correct tool.
Key point: should is chainable and retries the assertion against the current subject until it passes or the timeout expires; expect runs once and must be placed inside a .then() if it depends on a value from the queue, and it does not retry.
a. should and the retry model
cy.get(...).should(assertion) asserts against the subject (the element or value produced by the previous command) and retries the assertion until it passes or the timeout expires. The assertion is re-run against the subject, and the subject is re-queried if it is a DOM element, which is why should catches an element that appears after the initial query.
// Retries until the element contains "Saved"
cy.get('[data-cy="status"]').should('contain', 'Saved');
// Retries until the element is visible
cy.get('[data-cy="modal"]').should('be.visible');
// Retries until the element has the value
cy.get('[data-cy="email"]').should('have.value', 'a@b.com');
// Retries until the list has 3 items
cy.get('li').should('have.length', 3);
The retry is why should is the default assertion for a page that loads data. The command cy.get('[data-cy="status"]') also retries until the element exists, so the two retries compose: the element appears, and then the assertion on its text retries until the text is “Saved.”
The should assertion can be chained. cy.get('input').should('be.visible').and('have.value', 'hello') runs both assertions against the same subject. The .and() is an alias for .should() and runs the second assertion after the first passes.
cy.get('[data-cy="submit"]')
.should('be.visible')
.and('be.enabled')
.and('contain', 'Submit');
The assertion forms include Chai’s expect/assert chains (should('have.length', 3)), the jQuery assertions (should('be.visible')), and a callback form (should(($el) => { ... })) that receives the subject and can run arbitrary assertions on it. The callback form is the escape hatch when the built-in assertions do not express the condition.
b. expect and the .then() boundary
expect(value) is the Mocha/Chai assertion. It runs once, against the value it receives, and it does not retry. If the value is a chain object rather than a resolved value, the assertion fails in a confusing way.
// WRONG: expect on a chain object
cy.get('[data-cy="status"]').then(() => {
expect(cy.get('[data-cy="status"]')).to.contain('Saved'); // chain object
});
// RIGHT: expect inside .then() on the resolved value
cy.get('[data-cy="status"]').then(($el) => {
expect($el).to.contain('Saved'); // resolved element
});
The .then(($el) => { ... }) receives the resolved element as a jQuery object, and expect($el) runs once against it. The assertion does not retry, which means it fails if the element’s text has not yet updated. The should form is the correct choice when the value is expected to change.
expect is the correct tool when the value is already resolved and does not change. A value computed inside a .then(), a fixture loaded with cy.fixture(), a response body from cy.request()โthese are resolved, and expect is the assertion for them.
// Resolved fixture: expect is correct
cy.fixture('users.json').then((users) => {
expect(users).to.have.length(3);
});
// Resolved response: expect is correct
cy.request('/api/users').then((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.have.length(3);
});
The expect inside a .then() that returns a value becomes the subject for the next command, so the two styles compose. The should is for the chain; the expect is for the callback.
c. The retry configuration and the failure message
The retry timeout is controlled by defaultCommandTimeout, which is 4 seconds by default. The cy.get(..., { timeout: 10_000 }) option sets it per command, and the { timeout } argument on should sets it per assertion.
// Per-command timeout
cy.get('[data-cy="slow"]', { timeout: 10_000 }).should('be.visible');
// Per-assertion timeout
cy.get('[data-cy="slow"]').should('be.visible', { timeout: 10_000 });
The failure message names the assertion and the subject, and the command log shows the snapshot at the moment of failure. The message for a should that timed out is not the same as the message for an expect that failed: the should says “expected … but the assertion timed out,” and the expect says “expected … but got …”. The difference is the retry.
The .should() assertion is not the only retry mechanism. The cy.contains() command retries until an element containing the text exists, and the cy.get() command retries until the element exists. The should is the assertion that retries against the element the command found.
The should callback form is the way to assert on a property that the built-in assertions do not cover. The callback receives the subject and can use any Chai assertion on it.
cy.get('[data-cy="user"]').should(($el) => {
expect($el.attr('data-id')).to.match(/^\d+$/);
expect($el.text()).to.have.length.greaterThan(0);
});
The callback is not retried in the same way as the built-in assertions; it is retried as a whole. If the first assertion in the callback passes and the second fails, the whole callback re-runs on the next attempt.
Complete Example Session
// ============================================
// PART 1: should (RETRIES)
// ============================================
describe("status", () => {
it("waits for the saved message", () => {
cy.visit("/form");
cy.get('[data-cy="submit"]').click();
// Retries until the text contains "Saved"
cy.get('[data-cy="status"]').should('contain', 'Saved');
});
});
// ============================================
// PART 2: should CHAIN
// ============================================
describe("button", () => {
it("is visible and enabled", () => {
cy.visit("/");
cy.get('[data-cy="submit"]')
.should('be.visible')
.and('be.enabled')
.and('contain', 'Submit');
});
});
// ============================================
// PART 3: expect INSIDE .then()
// ============================================
describe("fixture", () => {
it("has three users", () => {
cy.fixture('users.json').then((users) => {
expect(users).to.have.length(3);
});
});
});
// ============================================
// PART 4: THE CALLBACK FORM
// ============================================
describe("callback", () => {
it("has a numeric data-id", () => {
cy.visit("/users");
cy.get('[data-cy="user"]').should(($el) => {
expect($el.attr('data-id')).to.match(/^\d+$/);
});
});
});
// ============================================
// PART 5: THE TIMEOUT
// ============================================
describe("timeout", () => {
it("waits for a slow element", () => {
cy.visit("/slow");
cy.get('[data-cy="result"]', { timeout: 10_000 }).should('be.visible');
});
});
The parts covered the retrying should, the chain, the expect inside .then(), the callback form, and the per-command timeout.
Quick Reference
Assertion Forms
| Form | Retries | Use For |
|---|---|---|
cy.get().should(...) | Yes | DOM assertions |
cy.get().and(...) | Yes | Additional assertion |
expect(value).to... | No | Resolved values |
.should(($el) => { ... }) | Yes (whole callback) | Custom assertions |
Common Assertions
| Assertion | Asserts |
|---|---|
should('be.visible') | Visible |
should('be.enabled') | Enabled |
should('contain', text) | Contains text |
should('have.value', v) | Input value |
should('have.length', n) | Count |
should('have.class', c) | Class |
Timeout
| Setting | Default |
|---|---|
defaultCommandTimeout | 4s |
cy.get(..., { timeout }) | Per command |
should(..., { timeout }) | Per assertion |
Best Practices
โ Do This:
// Use should for DOM assertions
cy.get('[data-cy="status"]').should('contain', 'Saved'); // โ
// Use expect for resolved values
cy.fixture('users.json').then((u) => expect(u).to.have.length(3)); // โ
// Set a longer timeout for a slow element
cy.get('[data-cy="slow"]', { timeout: 10_000 }).should('be.visible'); // โ
โ Don’t Do This:
// expect on an unresolved chain
cy.get('[data-cy="status"]').then(() => { expect(cy.get(...)).to... }); // โ
// should for a fixture value
cy.fixture('users.json').should('have.length', 3); // no subject // โ
// Hard-coded wait
cy.wait(2000); // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Flaky assertion on async data | expect used | Use should |
expect on a chain object | No .then() | Wrap in .then() |
| Timeout too short | Default 4s | Per-command timeout |
| Callback assertion passes on first check, fails on retry | The subject changed | Re-query or adjust the assertion |
Real-World Examples
1. should contains
cy.get('[data-cy="status"]').should('contain', 'Saved');
2. should visible
cy.get('[data-cy="modal"]').should('be.visible');
3. should value
cy.get('[data-cy="email"]').should('have.value', 'a@b.com');
4. should length
cy.get('li').should('have.length', 3);
5. and chain
cy.get('[data-cy="submit"]').should('be.visible').and('be.enabled');
6. expect inside .then()
cy.get('h1').then(($el) => expect($el).to.contain('Hi'));
7. expect on a fixture
cy.fixture('users.json').then((u) => expect(u).to.have.length(3));
8. Callback form
cy.get('[data-cy="user"]').should(($el) => expect($el.attr('data-id')).to.match(/^\d+$/));
9. Per-command timeout
cy.get('[data-cy="slow"]', { timeout: 10_000 }).should('be.visible');
10. expect on a response
cy.request('/api').then((r) => expect(r.status).to.eq(200));
Visual
should vs expect
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ should โ
โ cy.get(...).should('contain', 'Saved') โ
โ โ retries until the text contains "Saved" โ
โ โ re-queries the element โ
โ โ
โ expect โ
โ cy.get(...).then(($el) => { โ
โ expect($el).to.contain('Saved') โ
โ }) โ
โ โ runs once, fails immediately if not ready โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Retry Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ should('contain', 'Saved') โ
โ โ โ
โ โผ โ
โ Assert โ fail โ
โ โ โ
โ โผ โ
โ Wait, re-query, assert โ fail โ
โ โ โ
โ โผ โ
โ ... until pass or timeout โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The .then() Boundary
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cy.get('h1') โ subject: <h1> โ
โ .invoke('text') โ subject: "Welcome" โ
โ .then((text) => { โ
โ expect(text).to.equal('Welcome') // runs once โ
โ }) โ
โ โ
โ Inside .then(), the value is resolved. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Timeout
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ defaultCommandTimeout: 4s โ
โ โ
โ cy.get(..., { timeout: 10_000 }) โ
โ โ this command waits up to 10s โ
โ โ
โ should(..., { timeout: 10_000 }) โ
โ โ this assertion waits up to 10s โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Retrying assertion | should / and |
| Non-retrying assertion | expect |
expect placement | Inside .then() for chain values |
| Callback form | .should(($el) => { ... }) |
| Default timeout | 4s (defaultCommandTimeout) |
| Per-command timeout | cy.get(..., { timeout }) |
Key takeaways:
shouldretries;expectdoes not. Theshouldassertion re-runs against the subject until it passes or the timeout expires. Theexpectruns once against the value it receives.expectbelongs inside.then(). A value from acycommand is a chain object until it crosses the.then()boundary.expecton the resolved value inside the callback is the correct form.shouldis for DOM assertions;expectis for resolved values. A page that loads asynchronously needs the retrying assertion. A fixture or a response body is already resolved, andexpectis the assertion for it.- The callback form is the escape hatch.
.should(($el) => { ... })runs arbitrary Chai assertions against the subject and retries the whole callback. - The timeout is configurable per command and per assertion. The default is 4 seconds, and a slow element needs the
{ timeout }option.
Remember: The assertion choice is the difference between a test that waits and a test that races. Use should for anything that reads from the DOM, and use expect inside .then() for the values that are already resolved. The retry is the mechanism that replaces the hard-coded wait, and the callback form is the way to assert on the conditions the built-in assertions do not cover.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!