Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 35 ยท Async, Waiting and Flakiness

How Cypress Commands Really Work

Understand the Cypress command queue: why cy commands do not return values, how subjects flow through chains, and how then, as and wrap fix common bugs.

The first time you write Cypress tests, one rule surprises almost everyone: you cannot store the result of a cy command in a variable and use it on the next line. Code that looks perfectly normal, such as const title = cy.get('h1').text(), simply does not work. This is not a missing feature. It is a deliberate design, and once you see how it works inside, most of the "weird" Cypress behavior becomes obvious.

In this lesson you will learn what the command queue is, how a subject moves along a chain, how to get values out with .then(), .invoke() and aliases, and which commands retry and which do not. Then you will build a miniature command queue yourself, so the idea stops being magic. If you have not run a Cypress test yet, start with Your First Cypress Test.

The real Cypress needs Node.js, a browser and your app, so its code below is read-only. The runnable examples are stand-ins: a tiny queue that behaves like Cypress's in the ways that matter, but is not Cypress's source code.

Commands are queued, not executed

When Cypress runs your test function, the function runs from top to bottom instantly, in plain synchronous JavaScript. But each cy.something() call does not do its work at that moment. It only adds an entry to a queue and returns right away. Only after your test function has finished does Cypress start taking entries off the queue, one by one, waiting for each to finish before starting the next.

sequenceDiagram
  participant T as Test function
  participant Q as Command queue
  participant B as Browser
  T->>Q: cy.visit (enqueue)
  T->>Q: cy.get (enqueue)
  T->>Q: click (enqueue)
  Note over T: function ends
  Q->>B: run visit, wait
  Q->>B: run get, wait
  Q->>B: run click, wait

Your test body only builds the queue; the queue then runs the commands one at a time.

This is why plain JavaScript in the middle of a test behaves "too early":

JavaScript
// Cypress (read-only)
it('shows the price', () => {
  cy.visit('/product/7')
  console.log('A: after visit')          // prints FIRST, before the page loads
  cy.get('.price').then(($el) => {
    console.log('B: inside then')        // prints later, when the queue gets here
  })
  console.log('C: end of test body')     // prints right after A
})

The log order is A, C, B. The first two lines run while the queue is still being built; the callback inside .then() runs when the queue executes.

The queue in miniature

The stand-in below implements the idea in about 30 lines. Every method pushes an entry and returns the same object, so you can chain. run() is what Cypress does after your test body ends. Watch the order of the printed lines, and watch what happens to the variable price.

Node.js A miniature command queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Lines 1, 2 and 3 print first, and line 2 shows price still equal to 0. The .then() callbacks run during run(), so the variable only changes there. This is exactly why const text = cy.get('h1').text() cannot work: cy.get('h1') has not even run when the next line executes, and the value it will eventually find does not exist yet.

Subjects flow down a chain

Each queued command receives the result of the previous one. Cypress calls that result the subject. In cy.get('li').first().click(), get yields a set of li elements, first receives them and yields one, and click receives that one as its subject.

  • Some commands start a chain and ignore any subject: cy.visit(), cy.get(), cy.request(), cy.wrap().
  • Some commands need a subject: .click(), .type(), .should().
  • Some commands change the subject: .find(), .first(), .invoke(), .its().
  • .then(callback) receives the subject and, if the callback returns something, that becomes the new subject. If it returns nothing, the subject stays as it was.

In the stand-in, run() follows the same rule through the line if (result !== undefined) subject = result.

Getting values out of a chain

You never get values out by assigning. You keep working inside the chain, or you store the value with an alias.

JavaScript
// Cypress (read-only)
// WRONG: cy.get() does not return an element, and there is no .text() command
const text = cy.get('.price').text()

// RIGHT 1: use .then() and stay inside the callback
cy.get('.price').then(($price) => {
  const amount = parseFloat($price.text().replace('$', ''))
  expect(amount).to.be.greaterThan(0)
})

// RIGHT 2: .invoke() calls a method on the subject and yields the result
cy.get('.price').invoke('text').should('match', /^\$\d+/)

// RIGHT 3: an alias saves the subject for later commands
cy.get('.price').invoke('text').as('priceText')
cy.get('@priceText').then((text) => cy.log('Price was ' + text))

An alias created with .as('name') is looked up later with cy.get('@name'). The same mechanism powers network aliases such as cy.wait('@getUsers'), which you will meet in Intercepting and Mocking Network Requests. Aliases are also available as this.name inside regular function () {} callbacks (not arrow functions, because arrows do not have their own this).

When you need to put an ordinary value into a chain, use cy.wrap(). It queues a command that yields whatever you give it, which makes it possible to attach .should() or .then() to plain values and even to promises:

JavaScript
// Cypress (read-only)
cy.wrap({ name: 'Ada', roles: ['admin'] })
  .its('roles')
  .should('include', 'admin')

No async and await

Because Cypress commands are queue entries and not promises, putting await in front of one does nothing useful. Cypress commands are "thenable" (they have a .then method) but they are not real promises, and mixing the two styles is a classic source of confusing bugs. Do not write async test functions that await cy.get(...). Stay with chaining and .then(). If you need to call your own promise-returning function, wrap it: cy.wrap(fetchSomething()), and Cypress will wait for it before moving on.

This is the biggest difference from Playwright, where every action is an ordinary async call that you await. Auto-Waiting in Playwright covers that side.

What retries and what does not

Cypress retries in a very specific way, and knowing the rule saves hours of confusion:

  • Queries such as get, find, contains, first, eq, its and children read the page. If their result is missing, or an assertion after them fails, Cypress runs the whole query chain again, until it passes or the timeout (4 seconds by default) is reached.
  • Assertions (.should(), .and()) are what trigger the retry: they pull the previous queries into a loop.
  • Actions such as click, type and check run once, after waiting for the element to be actionable. They are never repeated automatically.
  • .then() runs its callback once. Nothing inside it is retried, so a check written with expect(...) inside .then() is a one-shot check.

That last point is the most common trap. Compare these two:

JavaScript
// Cypress (read-only)
// FLAKY: reads the list once, right now
cy.get('.item').then(($items) => {
  expect($items).to.have.length(3)
})

// STABLE: the assertion is part of the chain, so the query is retried
cy.get('.item').should('have.length', 3)

The next stand-in models the difference. A fake page fills its list after a few "ticks" of time. The one-shot check reads the list once and fails. The retrying check re-runs the query before each new attempt and passes on the fourth read.

Node.js One-shot check versus retrying assertion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The one-shot version fails with length 0 while the retrying version prints "PASS on attempt 4". Real Cypress waits in real time (checking about every 50 ms or so) rather than counting ticks, but the logic is the same: the assertion decides whether the query is run again.

Practical rules

  • Never assign a cy command's result to a variable and use it later; use .then(), .invoke(), .its() or .as().
  • Prefer .should() over .then() plus expect when you are waiting for the page to change.
  • Put the assertion at the end of the query chain it belongs to. Do not split a chain with an action in the middle and hope the earlier part retries.
  • Use cy.wrap() to bring plain values and promises into the queue.
  • Keep tests free of async/await; if a helper is async, wrap its promise.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does the code inside a cy.get('h1').then(callback) callback run?

    cy commands only add entries to a queue. The queue is executed after the test function ends, so the callback runs later than the plain JavaScript around it.
  2. 2. Why does const text = cy.get('.price').text() not work?

    The command is only queued. Use .then(), .invoke('text') or an alias to work with the value once it exists.
  3. 3. Which of these is retried automatically by Cypress?

    Assertions pull the preceding query chain into a retry loop. Callbacks in .then() and actions such as click run once.
  4. 4. What does .as('priceText') do?

    An alias stores the subject for later commands. It does not change the subject or assert anything.

Summary

  • cy commands enqueue work; the queue runs after your test function has finished.
  • Each command receives the previous command's result as its subject; .then() keeps the old subject if its callback returns nothing.
  • Get values out with .then(), .invoke(), .its() and .as(), never with assignment.
  • Queries plus assertions retry as a chain; actions and .then() callbacks run once.
  • Do not use async/await with Cypress commands; use cy.wrap() for promises.
  • The stand-in queue shows the logic; the real implementation also handles timeouts, logging and retries in real time.

Next: Auto-Waiting in Playwright