How to Fix Cypress Cannot Read Property Text of Null Errors in cy.log Callbacks
Learn why Cypress reports “text of null” near cy.log, how to read element text safely, and when to use should() versus then().

Short answer: cy.log() prints a message and yields null. It does not return the element or its text. Read text from the jQuery object yielded by a Cypress query, then pass the resulting string to cy.log(). If the text is an assertion, use a retriable .should() query instead.
cy.get('.message')
.invoke('text')
.then((text) => {
cy.log(text)
})
The phrase “Cannot read property text of null” only tells you that some expression attempted to access text on a null value. The null value may be the result of cy.log(), a missing variable, or a failed lookup. Read the stack trace and identify the exact expression before changing the test.
Why this error happens
Cypress commands are queued and yield subjects asynchronously. A DOM query such as cy.get() yields a jQuery collection, whose .text() method reads the element’s text content. By contrast, Cypress documents that cy.log(message) yields null and cannot be used as the subject of a following assertion or jQuery call.
// Wrong: cy.log() yields null, so .text() has no object to call.
cy.log('message').text()
// Wrong: this assumes cy.log returns the value passed to it.
cy.log(cy.get('.message')).text()
Use the query result as the subject, extract text, and only then log it:
cy.get('.message')
.invoke('text')
.then((text) => {
cy.log(text)
})
If the selector does not match, check the selector and rendering timing. Cypress queries retry while they are chained to assertions, subject to the command timeout. A .then() callback is for one-time dependent work; it does not keep retrying the preceding query.
Choose the correct Cypress pattern
Assert exact text with a retriable query
For a simple text check, prefer the built-in assertion. Cypress can retry the query and assertion until the expected text appears or the timeout expires.

cy.get('.message')
.should('have.text', 'Expected message')
Use contain.text when the element may include other text:
cy.get('.message')
.should('contain.text', 'Expected')
Log text once after the query succeeds
Use .invoke('text') followed by .then() when you want a string for logging or another one-time operation.
cy.get('[data-testid="status"]')
.invoke('text')
.then((text) => {
const value = text.trim()
cy.log(`Status: ${value}`)
})
.invoke('text') calls jQuery’s text() method on the yielded collection. Trimming is optional; use it only when whitespace is not meaningful.
Read text and make multiple retryable assertions
A callback passed to .should() is retried until its assertions pass. Cypress explicitly prohibits Cypress commands, including cy.log(), inside that callback.
cy.get('.profile')
.should(($profile) => {
const text = $profile.text()
expect(text).to.include('Ada')
expect(text).to.match(/Member since/)
})
Keep the callback synchronous: read from the jQuery object and use Chai or Sinon assertions. Move logging to a following .then() if you need it after the retryable assertion.
cy.get('.profile')
.should(($profile) => {
expect($profile.text()).to.include('Ada')
})
.then(($profile) => {
cy.log($profile.text())
})
Use native innerText when that is specifically required
jQuery .text() returns text content. If your test must use the browser’s rendered innerText, access the first DOM node from the jQuery collection:
cy.get('.message')
.should(($element) => {
const node = $element.get(0)
expect(node).to.exist
expect(node.innerText).to.equal('Expected message')
})
Do not substitute innerText merely to work around a null error. Pick it when visibility-aware, rendered text is the behavior under test.
Patterns that fail and their repairs
| Failing pattern | Why it fails | Repair |
|---|---|---|
cy.log('x').text() |
cy.log() yields null. |
Query the element first, then invoke text. |
cy.get('.x').should(() => { cy.log('x') }) |
Cypress commands are not allowed inside a .should() callback. |
Assert inside .should(); log in a following .then(). |
const text = cy.get('.x').text() |
Cypress commands do not return synchronous DOM values. | Use .invoke('text').then(...). |
cy.get('.x').then(() => expect(...)) for eventual UI text |
.then() runs once and breaks query retrying. |
Use .should('have.text', ...) or .should(callback). |
$element.text() when $element may be null |
The callback received no usable object or an earlier lookup returned null. | Check the selector, rendering conditions, and the stack-trace line. |

A complete example
describe('status message', () => {
it('asserts and logs the rendered message', () => {
cy.visit('/account')
// Retry until the element exists and has the expected text.
cy.get('[data-testid="status"]')
.should('have.text', 'Signed in')
.then(($status) => {
// .then() runs once after the assertion succeeds.
cy.log(`Account status: ${$status.text().trim()}`)
})
})
})
For a value that must be reused by Cypress commands, keep the work in the chain:
cy.get('[data-testid="order-id"]')
.invoke('text')
.then((orderId) => {
const id = orderId.trim()
expect(id).to.match(/^ORD-/)
cy.log(`Order: ${id}`)
cy.get('a.receipt').click()
})
Debugging checklist
- Read the code frame in the stack trace and locate the exact
.text()access. - Check whether the expression immediately before
.text()iscy.log()or another operation that yields null. - Confirm that the selector identifies the intended element and that the test is visiting the expected page.
- Decide whether the requirement is an assertion (use
.should()) or one-time logging (use.then()). - Remove Cypress commands from every
.should(callback)body. - If the application renders asynchronously, keep the query and assertion in one retryable chain.
- Reduce the test to the smallest failing case, then compare browser and environment settings if the problem remains.
Troubleshooting common errors
“Cannot read property ‘text’ of null” points at a log line
Verify that the log call is not being chained. Replace cy.log(value).text() with a query that yields a jQuery object, or log an already extracted string.
“Cypress command cannot be invoked from a should callback”
Move cy.log(), cy.get(), and other Cypress commands outside the callback. Keep only synchronous reads and assertions inside .should(($el) => { ... }).
The element exists later but the test times out
Use a selector that represents the element’s stable contract, such as a data-testid, and keep the assertion chained directly to cy.get(). Check that the element is not inside a different origin or iframe requiring the appropriate Cypress setup.
The log contains unexpected whitespace
.text() can include whitespace from nested nodes. Compare exact text with the expected whitespace, use .trim() for logging, or assert with contain.text when only a fragment matters.
The value is correct in the browser but stale in the test
A one-time .then() may run before the application finishes updating. Put the eventual condition in .should(); use .then() only after the condition has passed.
Performance, reliability, and maintainability
- Prefer one query. Chain the assertion and follow-up callback from the same
cy.get()when possible. - Use stable selectors. Classes tied to visual styling change more often than dedicated test attributes.
- Keep retryable callbacks small. Cypress may execute a
.should(callback)repeatedly, so avoid expensive parsing or side effects there. - Keep side effects in
.then(). Logging, clicking, and network calls belong after the condition succeeds. - Choose the narrowest text API.
have.textis concise for exact text,contain.texttolerates surrounding content, jQuerytext()reads text content, and nativeinnerTextreflects rendered text. - Do not increase timeouts first. A longer timeout cannot repair a null subject or a forbidden command in a
.should()callback. Fix the chain and selector first.
Or skip the browser setup
If your goal is to capture a page for a test artifact, visual review, or debugging record rather than interact with it in Cypress, ScreenshotNeo provides a single HTTP request. Its API accepts a URL and returns PNG, JPEG, WebP, or PDF. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.
See the ScreenshotNeo API documentation for all options, including full-page and element capture, device presets, custom JavaScript and CSS, waits, request blocking, authentication headers, PDFs, caching, async jobs, bulk capture, and signed links.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://stripe.com \
-o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', buffer);
An MCP server also lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots each month without a card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
FAQ
Does cy.log() return the text it prints?
No. Cypress documents that cy.log() yields null. Pass it a string obtained from a query instead.
Can I call cy.log() inside .should()?
No. Cypress forbids Cypress commands inside a .should(callback) function because the callback can be retried. Log in a following .then().
Should I use .invoke('text') or should('have.text')?
Use have.text for a direct retriable assertion. Use invoke('text') when you need the string for logging or other one-time code.
Why does the error mention null when the element is visible?
The null may come from a different expression, such as a chained cy.log() or a variable assigned synchronously. Follow the stack trace to the exact failing line.
Where are the official rules documented?
See Cypress’s cy.log() documentation, .should() documentation, text and jQuery examples in the Cypress FAQ, and the retry-ability guide.


