Q8 of 48 · Cypress
How do you write your first assertion in Cypress?
Short answer
Short answer: Chain `.should('assertion', value)` after a query like `cy.get(...)`. Cypress retries the chain until the assertion passes or the timeout (default 4s) expires. Most assertions use Chai under the hood: `be.visible`, `have.text`, `contain`, `have.length`, etc.
Detail
Cypress assertions are part of the command chain, not standalone statements. The pattern cy.get(selector).should('assertion', expected) is the building block — Cypress re-queries and re-asserts until the chain passes or times out.
The most common assertion shapes:
- Visibility / state:
should('be.visible'),should('be.disabled'),should('exist'),should('not.exist'). - Text / value:
should('have.text', 'Welcome'),should('contain', 'Welcome'),should('have.value', 'alice@x.com'). - Attributes / classes:
should('have.attr', 'href', '/dashboard'),should('have.class', 'is-active'). - Counts:
should('have.length', 3),should('have.length.greaterThan', 0).
Multiple assertions on the same subject chain with .and:
cy.get('[data-test=cart]').should('be.visible').and('contain', 'Apples')
Avoid expect(...) outside of .then blocks — those are Chai's standalone style and don't retry. Always prefer .should for retry-ability.
// EXAMPLE
assertions.cy.ts
it('asserts on the cart', () => {
cy.visit('/cart');
// Single assertion — retried for up to 4s
cy.get('[data-test=cart-row]').should('have.length', 3);
// Chained — both retry together
cy.get('[data-test=total]')
.should('be.visible')
.and('have.text', '£42.50');
// Negative assertion
cy.get('[data-test=empty-state]').should('not.exist');
// Attribute / class
cy.get('[data-test=checkout]')
.should('have.attr', 'href', '/checkout')
.and('not.have.class', 'is-disabled');
});