QA Interview Hub · Knowledge base · Quizzes · Українська

Cypress

Command queue and asynchrony

why there is no await

Why can't you write await cy.get() in Cypress?

Cypress commands do not run when called and are not Promises: they are put in a queue and run after the test body has finished. So await does nothing for them, and cy.get() returns not an element or a string but a chain object (Chainable). Ordinary JS runs immediately, before the commands, so values are taken with .then(), and a state that changes is checked with .should().

Cypress · Asynchrony

You write const text = await cy.get(...) like in Playwright and the test fails with a strange error. Why?

A developer used to Playwright or Jest brings the habit of putting await in front of every call. In Cypress it either does nothing or the test fails with a message that you returned a Promise and also invoked cy commands. This lesson explains why: what cy.get() actually does when it is called and when the command really runs.

How it works and why. According to the Cypress documentation, commands do not run when they are invoked. They are added to a queue and run after the test function has exited. The queue goes serially: each command waits until the previous one has finished together with its retries. Cypress commands are not Promises: you cannot await them, cannot race or parallelise them, and cannot attach a .catch. A failed command simply fails the test.

When cy.get() runs

1. The test body runscy.get() only adds a command to the queue2. The test body has endedall the plain JS has already run3. Cypress runs the queuecommands one by one, each waits for the last
Figure 1. The test body only builds the queue. Everything Cypress does with the browser happens after it.

This explains the "strange" order of execution. Plain JS (console.log, arithmetic, assignments) runs immediately while the test body is still executing, and Cypress commands wait for their turn:

it('execution order', () => {
  cy.visit('/cart');
  console.log('A');
  cy.get('h1').then(() => console.log('B'));
  console.log('C');
});
// in the console: A, C, B

In the same way, cy.get('h1').invoke('text') returns not a string but a chain object (a Chainable). The string appears only when Cypress reaches that command, and until then it does not exist.

Example: from await to .then and .should. A typical attempt "like in Playwright":

it('cart title', async () => {
  cy.visit('/cart');
  const text = await cy.get('h1').invoke('text');
  expect(text).to.contain('Cart');
});

An async function always returns a Promise, and Cypress does not allow returning a Promise from a test that also invoked cy commands: it shows an error about mixing the two. Even when such code sometimes "works", the execution order is not guaranteed. The correct version separates two jobs: getting a value and checking a state.

it('cart title', () => {
  cy.visit('/cart');
  // a value: in .then
  cy.get('h1').invoke('text').then((text) => {
    expect(text).to.contain('Cart');
  });
  // a check: in .should, which also retries
  cy.get('h1').should('contain', 'Cart');
});

The difference between them matters: in .then() the callback runs once, while .should('contain', ...) is retried until the check passes or the timeout ends. For a state that changes over time, the first form is fragile and the second is stable. More on this in the lesson about .then() and .should().

Limits and alternatives. The queue does not mean there is no asynchronous code in tests. A command result is taken through .then() or an alias, a Promise from your own code is wrapped in cy.wrap(), and what must run in Node (database, files) goes to cy.task(). Inside .then(async () => ...) you can await ordinary Promises, but not cy commands. If you really need async/await at every step, that is an argument for Playwright, not a reason to work around the queue.

And in Playwright:

The opposite: every action returns a real Promise and await is mandatory. The typical mistake there is a forgotten await: the action is not awaited and the test becomes flaky. The @typescript-eslint/no-floating-promises rule catches it.

const text = await page.locator('h1').textContent();
await expect(page.locator('h1')).toContainText('Cart');

Typical mistakes.

  • Writing await cy.get(...) and making the test async: this mixes a Promise with the command queue.
  • Assigning a command result to a variable (const el = cy.get(...)) and using it as an element or text: the variable holds only a Chainable.
  • Expecting plain JS after cy.get() to run after it: it runs earlier. Conditional logic that uses page values goes inside .then().
  • Adding cy.wait(1000) instead of fixing the order: the problem is not time but when the code runs.

Check yourself

A test has let total; cy.get('.total').invoke('text').then(t => { total = t }); console.log(total). What does the console print and why?

Answer

undefined. The test body runs completely before the queue starts, so console.log fires before .then assigns the value. Anything that depends on total must be inside .then() or in later queued commands.

Why can an async test with await cy.get() not be fixed by simply adding await before every command?

Answer

Cypress commands are not Promises: they are queued and the queue is run by Cypress itself after the test body. An async function returns a Promise, and Cypress forbids returning a Promise while also invoking cy commands. Take values with .then, check them with .should.

In the interview. Junior: Cypress commands do not return a Promise, they return a chainable object. Calling cy.get only puts a command into a queue, and Cypress itself runs the queue serially after the test body has finished. That is why await does not work here. I take values with then and check them with should, because should also retries. Middle/Senior: The queue gives Cypress control over waiting and retries, but the price is that plain JS and commands live in different "times". So I put anything that depends on a page value inside then, wrap a Promise from my own code in cy.wrap, and move Node code to cy.task. And if the project really needs async/await at every step, that is an argument for Playwright.

What is a subject and how do commands pass values along a chain?

A subject is the value one Cypress command yields to the next command in the chain. For example, cy.get yields a jQuery collection, .its('length') a number, .invoke('text') a string. A subject lives only within the chain, and after an action such as .click() it can go stale if the app re-rendered the DOM, so a new chain starts from cy. A value can be kept with .then() or an alias.

Cypress · Asynchrony

After .click() the chain suddenly works on a "dead" element. What exactly is passed between commands?

You read someone else's test: cy.get('.row').first().click().find('.badge'). It sometimes passes and sometimes fails with an error about a detached element. To understand why, you need to know what a subject is: the value one command hands to the next.

How it works and why. Every Cypress command "yields" a result, and the next command in the chain receives it as its subject. cy.get('li') yields a jQuery collection, .its('length') a number, .invoke('text') a string, cy.visit() the window object, cy.request() the response object. By their relation to the subject, commands come in three kinds: parent commands start a chain and need no previous one (cy.get, cy.visit, cy.request), child commands work only with the subject of the previous one (.click, .find, .should), and dual commands can do both (cy.contains searches the whole document or inside the yielded element).

A subject along a chain

cy.get('.cart-item')yields: a jQuery collection of elements.its('length')yields: a number.should('eq', 3)checks the number, yields the same one
Figure 1. Each command receives what the previous one yielded and yields its own: the type of the value changes along the way.

Actions like .click() and .type() usually yield the same element, and .should() usually yields the same subject it received (the exception: assertions like should('have.attr', 'href'), which yield the value). So a chain reads left to right: at each step ask yourself what is in the subject now.

cy.get('.cart-item')            // subject: all cart items
  .first()                      // subject: the first of them
  .find('.price')               // subject: the price inside
  .invoke('text')               // subject: a string
  .should('match', /\d+/);      // subject: the same string

Example: why a chain after an action is fragile. The documentation advises ending a chain after an action such as a click or a navigation and starting a new one from cy. The reason is practical. After a click the app may re-render the list, while the child command keeps working with the element the click yielded.

Fragile

Continuing the chain after a click

The subject after the click is the old element. If the framework replaced it, the lookup inside fails with a detached-element error.

Stable

A new chain from cy

cy.get() looks up the current elements again, and the query retries until the check goes green.

cy.get('.row').first().click().find('.badge').should('be.visible');
cy.get('.row').first().click();
// a new chain: the element is queried again
cy.get('.row').first().find('.badge').should('be.visible');

Reading the error: a chain after a click

1CypressError: cy.find() failed because the page updated as a result of this command, 2but you tried to continue the command chain. The subject is no longer attached to the DOM, and 3Cypress cannot requery the page after commands such as cy.find().
  1. What: the command after the click (find) failed, not the click itself. The problem is in the chain, not in the selector.
  2. Why: after the click the app re-rendered the page, and the chain kept working with the old element.
  3. Rule: Cypress requeries queries only. The subject of find came from the click action, so Cypress cannot find the row again, even though the message names cy.find() itself.

What to do

End the chain after the action and start a new one from cy: cy.get('.row').first().find('.badge').

Figure 2. The real error text (shortened): the numbers lead to the explanations.

Limits and alternatives. A subject lives only until the next command: you cannot "put it" in a variable and take it later. For that there is .then() (the value in a callback) and aliases through .as(), covered in a separate lesson. The .then() callback yields to the next command whatever it returns, and if it returns undefined, the result of the last cy command inside, or the previous subject. This is where a chain often changes type unexpectedly.

And in Playwright:

There is no subject chain. A locator is an ordinary object, you can keep it in a variable and narrow it (locator.locator()), and values come from await.

const row = page.locator('.row').first();
await row.click();
await expect(row.locator('.badge')).toBeVisible();

Typical mistakes.

  • Continuing a chain after .click() or another action when the DOM may have changed.
  • Assuming that .should() changes the subject: by default it stays the same.
  • Forgetting that cy.get() yields a jQuery collection, not an array or a string: take text through .invoke('text') or $el.text().
  • Trying to use the subject on the next line without .then(): it exists only inside the chain.

Check yourself

What does cy.get('.item').its('length') yield, and what is the subject after .should('eq', 3)?

Answer

its('length') yields a number (the count of elements). After .should('eq', 3) the subject stays the same number: should yields what it received.

Why does the documentation advise starting a new chain after .click()?

Answer

Because child commands after the click work with the element the click yielded. If the app re-rendered the DOM, that element is already detached. A new cy.get() looks the element up again.

In the interview. Junior: A subject is the result one command passes to the next in the chain. cy.get passes the found elements, its length a number, invoke text a string. Some commands start a chain, like cy.get or cy.request, others work with what came from the previous one, like find, click or should. Middle/Senior: What I keep in mind is that a subject lives only within a chain and can become stale after an action. So after a click I start a new chain from cy, and values I need to keep I take through then or an alias. The then callback also changes the subject by what it returns, and that is a common surprise.

How do you keep a value between commands: variables, .then, aliases?

Values are passed between Cypress commands in three ways: a closure in .then(), an alias with .as() and cy.get('@name'), or this in a regular function. A variable assigned outside the queue is empty, because the test body runs before the commands. An alias for the DOM stores the chain of queries rather than an element, so it survives re-rendering. Aliases are reset before every test, so they are created in beforeEach.

Cypress · Asynchrony

You saved a text into a variable and it is empty. How do you pass a value between Cypress commands correctly?

A test must compare the cart total before and after adding an item. The familiar const before = cy.get('[data-cy=total]').text() does not work: Cypress does not hand a value out to a variable. This lesson shows three working ways and when to choose which.

How it works and why. Commands are queued, so a "value" exists only after the queue has reached the command. Hence three ways. First: a closure through .then(), the value is available inside the callback and in all commands nested in it. Second: an alias through .as('name'), then cy.get('@name'). Third: this.name, but only in a regular function () {}, because an arrow function has no this of its own. Aliases are reset before every test, so they are created in beforeEach, not in before.

Three ways to keep a value

.then((v) => ...)the value in a callback, the simplest.as('name') + cy.get('@name')works in arrow functionsthis.name in function () {}this does not work in an arrow function
Figure 1. The simplest and most predictable way is a closure in .then; take an alias or this when the value is needed in several places of the test.

For the DOM an alias has one more property: Cypress stores not the element but the chain of queries, and every cy.get('@name') runs it again. So an alias survives the app re-rendering. For this reason the documentation advises putting an alias on the query, not after an action: .find(...).as('row').click() is good, .click().as('row') is not.

Example: compare the total before and after. First a closure, it covers most cases:

cy.get('[data-cy=total]').invoke('text').then((before) => {
  cy.get('[data-cy=add]').click();
  // before is available in the closure
  cy.get('[data-cy=total]').should(($el) => {
    expect(Number($el.text())).to.be.greaterThan(Number(before));
  });
});

And here a fixture bound to an alias, in two forms: through this and through cy.get('@user'):

beforeEach(() => {
  cy.fixture('user.json').as('user');
});

it('login', function () {      // function, not an arrow
  cy.get('[data-cy=email]').type(this.user.email);
});

it('the same through an alias', () => {
  cy.get('@user').then((user) => {
    cy.get('[data-cy=email]').type(user.email);
  });
});

The second form works in arrow functions and does not depend on the function type, so teams choose it more often. One more detail: cy.get('@user') yields the value stored by .as() and does not look for an element in the DOM when the alias is created on a fixture or a value.

Limits and alternatives. A plain let variable assigned in .then() works, but only where the code runs after the assignment, that is inside later callbacks. You cannot read it in the test body right away, because the body runs before the queue. Do not accumulate state in file-level variables between tests: tests must stay independent. For values needed in several files, a custom command or a fixture is better.

And in Playwright:

Aliases are not needed: the value goes into an ordinary variable, because await returns it right away.

const total = await page.getByTestId('total').textContent();
const user = JSON.parse(fs.readFileSync('data/user.json', 'utf8'));

Typical mistakes.

  • Assigning a command result to a variable and reading it in the test body: nothing has run there yet.
  • Using this.user in an arrow function: this will not be what you expect.
  • Creating an alias in before and being surprised it is missing in the second test: aliases are reset before every test.
  • Putting .as() after an action instead of on the query: the alias then holds a stale result of the action, not a chain of queries.
let total;
cy.get('[data-cy=total]').invoke('text').then((t) => { total = t; });
expect(total).to.eq('10'); // total is still undefined here

Check yourself

Why does expect(total) in the example above fail even though .then() really assigns total?

Answer

Because the test body runs completely before the queue starts: expect fires before .then assigns the value. Move the check inside .then() or into the next command.

A test with fixture('user.json').as('user') in before passes only the first time. What is wrong?

Answer

Aliases are reset before every test, so in the second test the user alias no longer exists. Create it in beforeEach.

In the interview. Junior: A plain variable from cy.get is not an element but a chainable, so you cannot do that. I pass the value through then or through an alias: I mark the result with as and get it with cy.get and an at sign. There is also this, but only in a regular function, because in an arrow function this is not the right one. Middle/Senior: An alias for the DOM stores a chain of queries, not an element, so it survives re-rendering. Aliases are reset before every test, so I create them in beforeEach. For one value I use a closure in then, and for a value needed in several places an alias.

How does .then() differ from .should() with a callback?

A callback in .should() is repeated until its assertions pass or the timeout ends, while a callback in .then() runs once. So a changing state is checked with .should(), and .then() is used to get a value and run further commands. A .should() callback must be safe to repeat, with no cy commands or side effects, and its return value is ignored.

Cypress · Asynchrony

The same expect passes in .should() but fails sometimes in .then(). What is the difference?

An order status updates about half a second after a click. In the test, .then(($el) => expect(...)) fails every other run, while .should(($el) => expect(...)) always passes. The difference is not syntax but how many times the callback runs.

How it works and why. The callback in .should() is repeated: Cypress runs the previous queries again (cy.get, .find and others) and the callback itself until all the assertions inside pass or the timeout ends, 4 seconds by default. The callback in .then() runs once, when the previous command has yielded a subject. So .then() is for getting a value and running the next commands, and .should(cb) is for many checks over one state that cannot be written as string assertions.

How many times the callback runs

should(cb): attempt 1 failedthe query and the callback are repeatedshould(cb): attempt 3 passedthe command is green, the subject is the samethen(cb): one attemptthe assert failed, the test fails at once
Figure 1. Should has room for the app to update, then does not: the first failed check stops the test.

This gives rules for a .should() callback. It may run many times, so it must be safe to repeat: no cy commands inside, no side effects, no accumulating state. A value it returns is ignored and the subject stays the one that arrived. In .then() it is the other way round: you can call cy commands inside, and the returned value becomes the new subject. Just do not mix the two: when the callback has cy commands, return the value through cy.wrap().

Example: the status after payment. Two forms with the same check:

// retried until the condition is true
cy.get('.status').should(($el) => {
  expect($el.text().trim()).to.eq('Paid');
});

// runs once: if the status has not updated yet, it fails
cy.get('.status').then(($el) => {
  expect($el.text().trim()).to.eq('Paid');
});

The second form passes only if the text has already changed by the time .then() runs. On a fast machine it will, on a slow CI it will not, so the test becomes flaky. And here is what must not go into .should():

cy.get('.row').should(($rows) => {
  cy.log('rows: ' + $rows.length); // error: a cy command inside should
  counter += 1;                    // side effect repeats on every retry
  expect($rows).to.have.length(3);
});

Here Cypress fails right away: invoking cy commands inside a .should() callback is forbidden. And the counter would grow as many times as there were retries, so its value is unpredictable. The right layout: first wait for the state through .should(), and only then take the value through .then().

cy.get('.row').should('have.length', 3);   // wait for the state
cy.get('.row').then(($rows) => {          // then take a value
  cy.log('rows: ' + $rows.length);
  return cy.wrap($rows.length);                    // the next subject: a number
});

Limits and alternatives. Simple checks need no callback at all: .should('have.text', 'Paid') or .should('have.length', 3) retry the same way and read better. A callback is needed when the check combines several conditions or needs a calculation, for example from a sum of prices. If you need to repeat not an assertion but your own logic (polling an API, other cy commands), there is no built-in retry for .then(): use cy.request in a recursive function or cy.waitUntil from a plugin.

And in Playwright:

The analogue of .should(cb) with retries is expect.poll() for a value or expect(async () => { ... }).toPass() for a block of assertions. A one-time check expect(await locator.textContent()).toBe(...) corresponds to .then in Cypress.

Typical mistakes.

  • Checking a changing state in .then(): the test depends on the speed of the app.
  • Calling cy commands or doing side effects inside a .should() callback.
  • Expecting the value returned from .should(cb) to go on: it is ignored.
  • Writing a long .should() callback when a string assertion would do.

Check yourself

A .should(cb) callback has counter++. Why is its value unpredictable at the end?

Answer

Because the should callback is repeated until the assertions pass, so counter grows on every attempt. A should callback must be safe to repeat: no side effects and no cy commands inside.

When do you take .then() rather than .should(cb)?

Answer

When you need to get a value once and run the next commands, for example cy commands that use it. For checking a state that changes over time, take .should.

In the interview. Junior: Should with a callback is repeated: Cypress looks the element up again and runs the check until the assertion passes. Then runs exactly once, it is for getting a value and continuing the chain. You must not call other cy commands inside should. Middle/Senior: A practical rule: a state that changes over time I check through should, and values I take through then. A should callback must be safe to repeat: no side effects and no counters. The value returned from it is ignored, while from then it becomes the new subject.

How do you combine Cypress with Promises and ordinary async code?

cy.wrap waits for a Promise, but the Promise is created when the function is called, so cy.wrap(fn()) starts fn at once. To make the call happen at the right moment, put it inside .then(). Code that must run in Node, such as a database or files, goes into cy.task. A test that calls cy commands must not return a Promise.

Cypress · Asynchrony

An async helper resets the database, but at the wrong moment. How do you combine Promises and the command queue in Cypress?

A project has a ready resetDb() function built on Promises that resets test data. It is called in a test through cy.wrap(resetDb()), and people are surprised: the reset happens before the cy.visit() that stands earlier. This lesson explains when ordinary code runs, how cy.wrap works with a Promise and where cy.task is needed.

How it works and why. cy.wrap(promise) adds a command to the queue that waits for the Promise. When the Promise settles, Cypress yields its value to the next command, and if it rejects, the test fails. The waiting time is limited by the timeout option, which defaults to defaultCommandTimeout. But the Promise itself is created when the function is called, that is at the moment the test body is still building the queue. So cy.wrap(resetDb()) starts resetDb() immediately, not after the earlier commands. The documentation directly recommends a chain through .then() for this case.

Where and when code runs

The test bodycy.wrap(resetDb()) calls resetDb() RIGHT AWAYThe Cypress queue in the browser.then(() => resetDb()) calls it when its turn comesThe Node processcy.task(...): database, files, tokens
Figure 1. The test body, the queue and the Node process are three different places and moments. Promise bugs are almost always about code started in the wrong place or at the wrong time.

For code that should not run in the browser at all (a database, the file system, token generation through a library), use cy.task(). The handler lives in the Node process, is defined in setupNodeEvents and returns a value or a Promise. The result comes back into the test as a subject.

Example: resetting the database. First the mistake:

cy.visit('/admin');           // queued
cy.wrap(resetDb());           // resetDb() starts now, before visit
cy.get('[data-cy=users]').should('have.length', 0);

Here the check expects an empty list, while the reset may have happened even before the page opened. The fix, where the Promise is created already inside the queue:

cy.visit('/admin');
cy.wrap(null).then(() => resetDb());  // a Promise at the right point of the queue
cy.get('[data-cy=users]').should('have.length', 0);

// or where the code must run in Node
cy.task('db:reset');

A handler for cy.task that lives outside the browser:

// cypress.config.ts
setupNodeEvents(on) {
  on('task', {
    'db:getUser': async ({ email }) => {
      return (await db.users.findOne({ email })) ?? null;
    },
  });
},

The result of cy.task('db:getUser', ...) can be checked right away: .its('status').should('eq', 'active'). The handler must return a value, and undefined is not allowed: return null.

Limits and alternatives. The main rule: do not mix Promise style and the queue in one block. Cypress does not allow returning a Promise from a test or a callback if cy commands are invoked inside, and it shows an error about mixing:

it('mixed', () => {
  return fetch('/api/ping').then(() => {
    cy.get('h1').should('be.visible'); // a cy command inside a returned Promise
  });
});

Inside .then(async () => { ... }) you can await Promises, but not cy commands. If the logic is complex, move it into cy.task (Node) or a custom command made of cy chains. For requests to the app itself, cy.request is often better than fetch: it uses browser cookies and works in the queue.

And in Playwright:

There is no mixing problem: it is plain async/await, so Promise.all and any libraries work. An analogue of cy.task is not needed, because the test already runs in Node: you can reach the database straight from the test.

For seniors. cy.wrap, cy.request and cy.task solve different problems. cy.wrap only waits for a Promise created in the browser. cy.request runs on the Cypress side, outside CORS limits, and suits calls to the application's API. cy.task runs code in Node, but its arguments and result must be serialisable (no functions or classes), and it has its own timeout, taskTimeout, 60 seconds by default, while defaultCommandTimeout is only 4. In a framework, async helpers that need Node live in setupNodeEvents and are called through a thin custom command, so tests do not know where the work runs.

Typical mistakes.

  • Writing cy.wrap(doSomething()) and assuming doSomething starts after the earlier commands.
  • Returning a Promise from a test where cy commands are invoked.
  • Calling cy commands inside an async .then() callback after await.
  • Querying the database from browser code instead of cy.task.

Check yourself

How does cy.wrap(getToken()) differ from cy.wrap(null).then(() => getToken())?

Answer

In the first case getToken() is called immediately while the queue is being built, before the earlier cy commands. In the second the call happens in the queue, after the earlier commands, and Cypress waits for the Promise returned from then.

When do you need cy.task rather than cy.wrap?

Answer

When the code must run in Node, not in the browser: a database, files, libraries that do not work in a browser. cy.wrap only waits for a Promise created in the browser code of the test.

In the interview. Junior: For Promises there is cy.wrap: I wrap the Promise, Cypress waits for it in the queue and passes the value on. Code that must run in Node, such as database queries, I move to cy.task. The main thing is not to mix the Cypress queue with await in one place. Middle/Senior: The catch in cy.wrap(fn()) is that the function is called while the queue is being built, not at the right moment. So I put the call inside then, and Cypress waits for the returned Promise. Complex asynchronous logic I move to cy.task or a custom command, because Cypress does not allow returning a Promise from a test that has cy commands.

The asynchrony of Cypress commands

Cypress commands do not run when called but go into a queue that starts after the test body finishes. Hence three places: ordinary JS in the test body runs at once and builds the queue, commands and the .then and .should callbacks run in the queue, and Node code goes through cy.task. Most bugs with variables and Promises come from mixing these places.

Cypress · Asynchrony

A chain of commands looks like ordinary code but behaves differently. What short model explains it?

This lesson sums up the chapter. If you read a Cypress test as ordinary JS from top to bottom, it seems to break expectations: variables are empty, await does not work, an if on an element guesses wrong. Below is a model of three "places" that explains almost everything.

How it works and why. According to the documentation, Cypress commands do not run when they are called: they go into a queue that starts after the test body finishes, command by command. So there are three places: at once runs ordinary JS in the test body (which also builds the queue), in the queue run the commands and the .then and .should callbacks, and in the Node process runs what the browser cannot do, through cy.task. Every unusual symptom is a mix of these places.

Three places of execution

At onceplain JS in the test body, building the queueIn the queuecy commands, .then, .should: one by oneIn Nodecy.task, setupNodeEvents
Figure 1. Plain JS runs earlier than the commands: anything that depends on command results must stand in the queue.

Example: a condition on page state. Beginners write if (cy.get('banner').length), and it does not work: cy.get() returns a Chainable that has no such property, and when the body runs the element has not been looked up yet. The condition must stand in the queue:

cy.get('body').then(($body) => {
  // conditional logic on page state: inside .then
  if ($body.find('[data-cy=banner]').length) {
    cy.get('[data-cy=close-banner]').click();
  }
});

Here .then receives body, and $body.find() searches synchronously: it neither waits nor fails when there is no banner. cy.get('[data-cy=banner]').then(...) does not fit here: with no banner cy.get() fails after the timeout. For conditions on a state that may change, the Cypress documentation in general advises not to build tests on them, because they are unstable.

A quick choice of tool:

What you needWhat to use
Wait for a state to change.should(...)
Take a value once.then(cb)
A value in several places.as() and cy.get('@name')
Your own Promisecy.wrap(null).then(() => p())
Code in Nodecy.task()

Limits and alternatives. This model gives reliable retries and shorter tests, but it sometimes makes code with branching and loops unnatural: a loop over elements is better written with .each(), not for. If tests need real asynchronous logic at every step, that points to Playwright, where async/await replaces the queue.

And in Playwright:

There is no command queue: code runs top to bottom and await returns the result at once. A condition like if (await banner.count()) works the way it reads.

Typical mistakes.

  • Reading a command result in the test body, outside .then.
  • Putting an if on an element outside the queue.
  • Adding cy.wait(ms) instead of the right order and the right wait.
  • Mixing async/await with commands in one block.

Check yourself

Why does if (cy.get('.banner').length) not work?

Answer

Because cy.get() does not return elements: it puts a command in the queue and returns a Chainable, and the test body runs before the queue. A condition on page state goes inside .then().

Where does a plain console.log placed between two cy commands run?

Answer

Right away, while the test body is still building the queue, that is before both commands. To print something at the right point of the queue, use cy.log or console.log inside .then().

In the interview. Junior: Cypress commands do not run at once, they are queued and run serially after the test body. They return a chainable, not a Promise, so await does not work. I take values through then, and to keep them I use an alias. Middle/Senior: I have a simple model of three places: plain JS runs at once, commands and callbacks run in the queue, and Node code goes through cy.task. Most bugs with variables, ifs on elements and Promises are a mix of these places.