Assertions
Verify DOM state, content, visibility, and custom Chai assertions in Cypress.
Implicit and Explicit Assertions
Should and and chain on Cypress commands retry until pass or timeout. Implicit assertions built into commands; explicit use expect for standalone values.
Separate act commands from assert should—click then assert URL rather than chaining should on click return value incorrectly.
cy.get('[data-cy="status"]').should("have.text", "Active");
cy.get('[data-cy="items"]').should("have.length", 3);
expect(interceptedBody).to.deep.equal({ ok: true });Element Assertions
Matchers include be.visible, be.disabled, have.class, have.attr, have.css, and have.value. Negate with .should("not.exist") for removed elements.
have.text compares text content; contain.text allows substring. Trim whitespace sensitivity matters for text assertions.
cy.get('[data-cy="banner"]')
.should("be.visible")
.and("have.class", "alert-success")
.and("contain.text", "Saved");Content and Visibility
Elements may exist but be hidden via CSS—distinguish exist vs visible. aria-hidden elements fail visibility checks appropriately.
For lists, have.length asserts count; each can iterate with .each callback asserting row content.
- Use should with callback for complex multi-property checks
- Multiple should on same subject chain retries all
- Avoid hard-coded timeouts before should—should retries built in
cy.get('[data-cy="modal"]').should("not.exist");
cy.get('[data-cy="skeleton"]').should("not.be.visible");Network and Stub Assertions
cy.wait("@alias") asserts request occurred; inspect cy.get("@alias").its("request.body") for payload. Combine with intercept stubs to verify API contract from UI flow.
Assert status code on intercept response stub matches app expectations for error handling tests.
cy.wait("@createUser").its("response.statusCode").should("eq", 201);
cy.get("@createUser").its("request.body.email").should("eq", "ada@example.com");Custom Assertions
Extend Chai in support file for domain matchers. Cypress bundles chai, sinon-chai, and jQuery assertions.
Keep custom assertions readable—complex logic belongs in helper functions returning boolean with clear failure messages.
chai.use((_chai, utils) => {
_chai.Assertion.addMethod("validUuid", function () {
const uuid = utils.flag(this, "object");
this.assert(
/^[0-9a-f-]{36}$/i.test(uuid),
"expected #{this} to be a UUID"
);
});
});