| | |

Cypress 06 ๐ŸŒฒ The Command Queue โ€” Chaining and Asynchronous Execution Model

โฑ๏ธ Estimated read: 9 min | |

Cypress tests are written as chains of cy commands, and the chains execute in a queue rather than in the order the JavaScript statements appear to run. The test function enqueues the commands and returns; the queue then runs them one at a time, waiting for each to finish before starting the next. The model is what enables the retry and the time-travel debugging, and it is the source of the confusion that makes a const assignment from a cy command hold a chain object instead of a value.

This chapter covers the command queue’s execution model, the chaining that builds it, and the .then() and alias patterns that extract a value from the queue. The sections that follow walk through the queue’s mechanics, the return values that are not values, and the patterns that keep a test readable when the data must cross the queue boundary.

Key point: cy commands enqueue work and return a chain object, not a Promise; the test function returns before the queue runs, a value from a command is available only inside .then() or through an alias, and the queue executes the commands in order with retry.


a. The queue’s execution model

A Cypress test function runs to completion before any cy command executes. Each cy call appends a command to the queue and returns a chainable object. When the function returns, Cypress starts the queue and runs the commands in order, waiting for each to finish before starting the next.

it("demonstrates the queue", () => {
  cy.visit("/");                          // enqueued
  cy.get("h1").should("contain", "Hi");   // enqueued
  console.log("after enqueue");           // runs BEFORE the commands
});

The console.log runs first, then visit, then get, then the assertion. The order is not the order of the statements in the function; it is the order the statements ran (enqueue) followed by the order the queue runs (execute). The distinction is the model.

The queue is why a cy command cannot be awaited. The command returns a chain object synchronously, and await on a non-Promise resolves immediately. The await does not wait for the command; the queue does.

// WRONG: await does not wait for the queue
it("awaits a cy command", async () => {
  await cy.visit("/");        // resolves immediately
  cy.get("h1");               // runs after, but not because of the await
});

// RIGHT: chain the commands
it("chains", () => {
  cy.visit("/").get("h1").should("contain", "Hi");
});

The queue also holds the retry. A command like cy.get("h1") retries until the element exists, and the next command does not start until the retry succeeds or the timeout expires. The retry is per command, and the queue is what sequences it.


b. Chaining and the subject

A cy command returns a chain object, and the next command in the chain receives the previous command’s result as its subject. cy.get("input").type("hello") gets the input and passes it to type. The .then() callback receives the subject and can return a new value that becomes the subject for the next command.

cy.get("input")
  .type("hello")
  .should("have.value", "hello");

The subject is the implicit argument. The .should() assertion receives the element as its subject and retries the assertion against it. The .then() callback receives the subject and can assert on it with the raw value.

The .then() is the boundary where the chain becomes a plain JavaScript callback. Inside the callback, the subject is a real valueโ€”a DOM element, a string, a numberโ€”and the code can use it like any other value. The callback’s return value becomes the subject for the next command.

cy.get("h1")
  .invoke("text")
  .then((text) => {
    // text is a string here
    expect(text).to.equal("Welcome");
    return text.toUpperCase();
  })
  .should("equal", "WELCOME"); // receives the returned value

The .invoke("text") calls the jQuery .text() method on the element and passes the result to .then(). The callback returns the uppercase string, which becomes the subject of the .should().

The .wrap() command is the way to put a plain value back into the chain. A value computed inside a .then() is not automatically a subject; cy.wrap(value) makes it one.

cy.get("input").then(($input) => {
  const value = $input.val();
  cy.wrap(value).should("equal", "hello");
});

c. Aliases and the data that crosses commands

An alias is the mechanism for a value that must be used later in the test, outside the callback where it was produced. The .as("name") call stores the subject under a name, and cy.get("@name") retrieves it.

cy.get("h1").invoke("text").as("heading");
cy.get("@heading").then((text) => {
  expect(text).to.equal("Welcome");
});

The alias is resolved at the point of use, not at the point of definition. A cy.get("@heading") later in the test waits for the aliased command to complete and retrieves its result. The alias is the pattern for sharing a value between commands without nesting the callbacks.

The cy.fixture() command is the alias source for test data. A fixture loaded with .as("users") is available as cy.get("@users"), and the data is available in a .then().

beforeEach(() => {
  cy.fixture("users.json").as("users");
});

it("uses the fixture", function () {
  cy.get("@users").then((users) => {
    expect(users).to.have.length(3);
  });
});

The function () form is required for this.users, which is the alias made available on the test context. The arrow function does not bind this, so the alias is not accessible.

The cy.intercept() alias is the third use. An intercepted request is aliased with .as("getUsers"), and cy.wait("@getUsers") waits for the request to complete. The wait is the synchronization point for a test that needs the network to settle before the assertion.


Complete Example Session

// ============================================
// PART 1: THE QUEUE
// ============================================
describe("queue", () => {
  it("runs commands in order", () => {
    cy.visit("/");                          // enqueued
    cy.get("h1").should("contain", "Hi");   // enqueued
    console.log("before");                  // runs first
  });
});

// ============================================
// PART 2: THE SUBJECT AND .then()
// ============================================
describe("subject", () => {
  it("extracts text", () => {
    cy.get("h1")
      .invoke("text")
      .then((text) => {
        expect(text).to.equal("Welcome");
        return text.toUpperCase();
      })
      .should("equal", "WELCOME");
  });
});

// ============================================
// PART 3: THE ALIAS
// ============================================
describe("alias", () => {
  beforeEach(() => {
    cy.fixture("users.json").as("users");
  });

  it("uses the fixture", function () {
    cy.get("@users").then((users) => {
      expect(users).to.have.length(3);
    });
  });
});

// ============================================
// PART 4: THE INTERCEPT
// ============================================
describe("intercept", () => {
  it("waits for the request", () => {
    cy.intercept("GET", "/api/users").as("getUsers");
    cy.visit("/users");
    cy.wait("@getUsers");
    cy.get("li").should("have.length", 3);
  });
});

The parts covered the queue order, the .then() extraction, the fixture alias, and the intercept wait.


Quick Reference

Queue Mechanics

BehaviorDetail
cy returnsChain object, not Promise
Test functionReturns before commands run
ExecutionQueue, in order
RetryPer command

Chaining

MethodReceivesReturns
.then(fn)SubjectCallback’s return
.invoke(method, ...args)SubjectMethod result
.should(matcher)SubjectSubject
.wrap(value)โ€”Value as subject

Aliases

CallPurpose
.as("name")Store the subject
cy.get("@name")Retrieve it
cy.fixture(...).as("name")Alias test data
.as("request") on interceptWait with cy.wait

Best Practices

โœ… Do This:

// Chain the commands
cy.get("input").type("hello").should("have.value", "hello");  // โœ…

// Extract with .then()
cy.get("h1").invoke("text").then((t) => expect(t).to.equal("Hi")); // โœ…

// Alias the fixture
cy.fixture("users.json").as("users");                         // โœ…

โŒ Don’t Do This:

// Assign the chain object
const text = cy.get("h1").invoke("text"); // not a string       // โŒ

// Await a cy command
await cy.visit("/"); // does not wait for the queue             // โŒ

// Use an arrow function for the alias context
it("...", () => { this.users; }); // this is not the test context // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Value is a chain objectAssigned cy resultUse .then() or alias
await cy does nothingCypress does not return PromisesChain the commands
Alias undefinedArrow functionUse function ()
Assertion runs before dataNo cy.wait on the interceptAlias and wait

Real-World Examples

1. Chain

cy.visit("/").get("h1").should("contain", "Hi");

2. Extract text

cy.get("h1").invoke("text").then((t) => expect(t).to.equal("Hi"));

3. Return from .then

cy.get("h1").invoke("text").then((t) => t.toUpperCase()).should("equal", "HI");

4. Alias

cy.get("h1").invoke("text").as("heading");

5. Retrieve

cy.get("@heading").then((t) => { ... });

6. Fixture

cy.fixture("users.json").as("users");

7. cy.wrap

cy.wrap(42).should("equal", 42);

8. Intercept wait

cy.intercept("GET", "/api").as("get"); cy.wait("@get");

9. this alias

it("...", function () { cy.get("@users").then((u) => { ... }); });

10. Chain assertion

cy.get("li").should("have.length", 3);

Visual

The Queue

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  TEST FUNCTION                                          โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
โ”‚  โ”‚ cy.visit("/")       โ†’ enqueue            โ”‚           โ”‚
โ”‚  โ”‚ cy.get("h1")        โ†’ enqueue            โ”‚           โ”‚
โ”‚  โ”‚ .should("exist")    โ†’ enqueue            โ”‚           โ”‚
โ”‚  โ”‚ console.log("x")    โ†’ runs now           โ”‚           โ”‚
โ”‚  โ”‚ return                                   โ”‚           โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  QUEUE RUNS                                             โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
โ”‚  โ”‚ 1. visit /                               โ”‚           โ”‚
โ”‚  โ”‚ 2. get h1 (retry until exists)           โ”‚           โ”‚
โ”‚  โ”‚ 3. assert exists (retry until pass)      โ”‚           โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Subject

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  cy.get("input")  โ†’ subject: <input>                     โ”‚
โ”‚    .type("hello") โ†’ subject: <input>                     โ”‚
โ”‚    .should("have.value", "hello")                        โ”‚
โ”‚                                                         โ”‚
โ”‚  cy.get("h1")      โ†’ subject: <h1>                       โ”‚
โ”‚    .invoke("text") โ†’ subject: "Welcome"                  โ”‚
โ”‚    .then((t) => { ... })                                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

.then() Boundary

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  cy.get("h1").invoke("text").then((text) => {           โ”‚
โ”‚    // text is a real string here                        โ”‚
โ”‚    expect(text).to.equal("Welcome");                    โ”‚
โ”‚    return text.toUpperCase();                           โ”‚
โ”‚  }).should("equal", "WELCOME");                         โ”‚
โ”‚                                                         โ”‚
โ”‚  The callback's return becomes the next subject.        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Alias Resolution

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  cy.fixture("users.json").as("users");                  โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  alias "users" โ†’ fixture data                           โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  cy.get("@users").then((users) => { ... });             โ”‚
โ”‚                                                         โ”‚
โ”‚  Resolved at use, waits for the aliased command.        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Command returnChain object, not Promise
ExecutionQueue, after the test function returns
SubjectPrevious command’s result
Extract value.then() or alias
Alias.as("name") / cy.get("@name")
Wait for networkcy.wait("@interceptAlias")

Key takeaways:

  • cy commands enqueue work; they do not run it immediately. The test function returns before the queue starts, which is why a console.log in the function body runs before the cy.visit it appears to precede.
  • The chain carries a subject. Each command receives the previous command’s result, and .then() is the boundary where the subject becomes a plain JavaScript value.
  • A cy result is not a value. const text = cy.get("h1").invoke("text") assigns the chain object, not the text. The value is available inside .then() or through an alias.
  • Aliases cross the queue boundary. .as("name") stores the subject, and cy.get("@name") retrieves it later, waiting for the aliased command to complete.
  • cy.wait("@alias") synchronizes the network. An intercepted request is aliased, and the wait is the point where the test knows the response has arrived.

Remember: Cypress tests are a queue, not a sequence of awaited statements. The chain builds the queue, the queue runs the commands, and the retry is per command. To get a value out, use .then() or an alias. To wait for a network, alias the intercept and cy.wait. Do not await a cy command, do not assign its result synchronously, and do not assume the statement order is the execution order.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!