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

Cypress › Command queue and asynchrony

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.

More articles in this chapter