Cypress 06 ๐ฒ The Command Queue โ Chaining and Asynchronous Execution Model
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
| Behavior | Detail |
|---|---|
cy returns | Chain object, not Promise |
| Test function | Returns before commands run |
| Execution | Queue, in order |
| Retry | Per command |
Chaining
| Method | Receives | Returns |
|---|---|---|
.then(fn) | Subject | Callback’s return |
.invoke(method, ...args) | Subject | Method result |
.should(matcher) | Subject | Subject |
.wrap(value) | โ | Value as subject |
Aliases
| Call | Purpose |
|---|---|
.as("name") | Store the subject |
cy.get("@name") | Retrieve it |
cy.fixture(...).as("name") | Alias test data |
.as("request") on intercept | Wait 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Value is a chain object | Assigned cy result | Use .then() or alias |
await cy does nothing | Cypress does not return Promises | Chain the commands |
| Alias undefined | Arrow function | Use function () |
| Assertion runs before data | No cy.wait on the intercept | Alias 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
| Item | Value |
|---|---|
| Command return | Chain object, not Promise |
| Execution | Queue, after the test function returns |
| Subject | Previous command’s result |
| Extract value | .then() or alias |
| Alias | .as("name") / cy.get("@name") |
| Wait for network | cy.wait("@interceptAlias") |
Key takeaways:
cycommands enqueue work; they do not run it immediately. The test function returns before the queue starts, which is why aconsole.login the function body runs before thecy.visitit 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
cyresult 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, andcy.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.
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!