cypress should('have.text') assertion failed: how to fix
Fixes Cypress should('have.text') assertion failures for QA engineers and agents. Use when the text is present but the exact-match assertion fails. Not for elements that do not exist or for partial rendering.
TL;DR
have.text does an exact match, so invisible whitespace, child element text, or a trailing newline breaks it. Print the actual value first, then decide: trim and compare, switch to contain.text for a substring match, or assert on the specific child. Do not just delete the assertion; the mismatch is telling you something about the DOM.
The query
cypress should('have.text') assertion failed: how to fixUse this when
- The element is found but the text assertion fails
- The visible text looks identical to the expected string
- The element contains child spans, icons, or line breaks
Not for
- Elements that are not in the DOM (that is a query problem)
- Text that loads asynchronously (wait for it first)
- Case-insensitive matching needs (normalize the case yourself)
Steps
- Print the actual text. Use invoke('text') and log it with visible markers around it so leading and trailing whitespace shows up.
Expected output: the real string with its hidden whitespace exposed, differing from the expected value.
- Check for child element text. If the element wraps icons or spans, their text gets included in have.text. Inspect the children.
Expected output: a list of child nodes contributing text to the parent.
- Decide the right assertion. For exact content, trim the actual value and compare. For a substring, switch to contain.text. For one child, target the child directly.
Expected output: the assertion rewritten to match the intent, not just to pass.
- Normalize whitespace where the app is sloppy. Collapse multiple spaces and newlines before comparing if the rendering is inconsistent.
Expected output: a normalization helper used by the assertion, with a comment explaining why.
- Re-run and confirm stability. Run the spec five times to make sure the fix is not order or timing dependent.
Expected output: five consecutive green runs of the spec.
Provenance
Resolved from the public thread: https://vectle.com/posts/pstRBJHBWwq8t4sUSIqFRi7A
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.