| | |

Cypress 13 ๐ŸŒฒ Aliases โ€” cy.as() and Reusable Selectors or Requests

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

An alias is a name for a value that crosses the command queue. The .as("name") call stores the previous command’s subject under a name, and cy.get("@name") retrieves it laterโ€”after the queue has advanced past the point where the value was produced. The mechanism is the answer to the queue’s central constraint: a value from a cy command is not available synchronously, and an alias is how the test keeps a reference to it without nesting every subsequent command inside a .then().

This chapter covers the three alias sourcesโ€”the DOM subject, the intercept, and the fixtureโ€”and the cy.get("@alias") patterns that use them. The sections that follow walk through aliasing a subject, aliasing a network request, and the this.alias context form that makes an alias available inside a test without the cy.get chain.

Key point: .as("name") stores the previous command’s subject under a name, cy.get("@name") retrieves it, cy.wait("@alias") blocks on an aliased intercept, and the alias is resolved at the point of useโ€”not at the point of definition.


a. Aliasing a DOM subject

The .as("name") after a cy.get stores the element under a name. The subsequent cy.get("@name") retrieves it, and the commands that follow operate on the stored element rather than re-querying the DOM.

cy.get('[data-cy="email"]').as("emailInput");

cy.get("@emailInput").type("user@example.com");
cy.get("@emailInput").should("have.value", "user@example.com");

The value of the alias is the stability. A cy.get('[data-cy="email"]') re-queries the DOM each time it runs, which is the correct behavior when the element may be replaced. An alias stores the element from the first query, which is the correct behavior when the test wants the same element across several assertions.

The alias also works on a value extracted from an element. A cy.get("h1").invoke("text").as("heading") stores the text, and cy.get("@heading") retrieves the string.

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

The cy.get("@alias") re-runs the aliased command chain, which is the detail that matters. An alias on cy.get("h1").invoke("text") re-queries the h1 and re-extracts the text when the alias is retrieved. The value is not a snapshot; it is a lazy reference to the command chain.


b. Aliasing an intercept and a fixture

The .as("name") on a cy.intercept names the request, and cy.wait("@name") waits for it. The intercept alias is the synchronization point for a test that needs the network to settle.

cy.intercept("GET", "/api/users").as("getUsers");
cy.visit("/users");
cy.wait("@getUsers").its("response.statusCode").should("eq", 200);

The .as("name") on a cy.fixture stores the fixture data, and cy.get("@name") retrieves it. The this.name form is the other way to access a fixture alias, and it requires the test function to be a function () rather than an arrow function, because the alias is bound to the test context’s this.

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

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

  // or via the test context
  const users = this.users;
  expect(users).to.have.length(3);
});

The this.users form is the reason the test function is a function (). An arrow function does not bind this, and this.users is undefined. The cy.get("@users").then(...) form works with either function type, which is why it is the safer pattern.

The aliased intercept and the aliased fixture can share a name scope. A cy.intercept(...).as("getUsers") and a cy.fixture("users.json").as("users") are two different names, and the cy.wait("@getUsers") and cy.get("@users") retrieve them independently.


c. The this context and the alias lifecycle

The aliases are stored on the test context, and the this.alias form is the direct access. The beforeEach that creates the alias and the test that reads it are the same test context, which is why the fixture alias is available as this.users in the test body.

The alias is cleared between tests. A beforeEach that creates the alias runs before each test, so each test gets a fresh alias. A before hook that creates the alias runs once, and the alias is available in every test in the block.

before(function () {
  cy.fixture("users.json").as("users"); // once, available to all
});

it("uses the shared fixture", function () {
  expect(this.users).to.have.length(3);
});

The cy.get("@alias") in a beforeEach is the pattern for a setup that depends on a prior command. A beforeEach that visits a page and aliases an element makes the element available to every test in the block.

beforeEach(() => {
  cy.visit("/dashboard");
  cy.get("h1").as("heading");
});

it("checks the heading", () => {
  cy.get("@heading").should("contain", "Dashboard");
});

The alias is the mechanism for the reusable selector. A page object can alias the elements it queries, and the tests retrieve them by name. The pattern is the same as a data-cy attribute, with the difference that the alias is scoped to the test rather than the DOM.


Complete Example Session

// ============================================
// PART 1: THE SUBJECT ALIAS
// ============================================
describe("subject", () => {
  it("aliases an input", () => {
    cy.visit("/form");
    cy.get('[data-cy="email"]').as("emailInput");
    cy.get("@emailInput").type("user@example.com");
    cy.get("@emailInput").should("have.value", "user@example.com");
  });
});

// ============================================
// PART 2: THE INTERCEPT ALIAS
// ============================================
describe("intercept", () => {
  it("waits for the request", () => {
    cy.intercept("GET", "/api/users").as("getUsers");
    cy.visit("/users");
    cy.wait("@getUsers").its("response.statusCode").should("eq", 200);
  });
});

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

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

  it("uses this", function () {
    expect(this.users).to.have.length(3);
  });
});

// ============================================
// PART 4: THE REUSABLE SELECTOR
// ============================================
describe("reusable", () => {
  beforeEach(() => {
    cy.visit("/dashboard");
    cy.get("h1").as("heading");
  });

  it("checks the heading", () => {
    cy.get("@heading").should("contain", "Dashboard");
  });
});

The parts covered the subject alias, the intercept alias, the fixture alias in both forms, and the reusable selector.


Quick Reference

Alias Sources

SourceExample
DOM subjectcy.get(sel).as("el")
Extracted valuecy.get(sel).invoke("text").as("text")
Interceptcy.intercept(...).as("req")
Fixturecy.fixture("f.json").as("data")

Retrieval

FormUse
cy.get("@name")Retrieve the alias
cy.wait("@name")Wait on an intercept
this.nameDirect access (requires function ())

Function Type

Test Functionthis Available
function () {}Yes
() => {}No

Best Practices

โœ… Do This:

// Alias the subject and retrieve it
cy.get('[data-cy="email"]').as("email");
cy.get("@email").type("a@b.com");                              // โœ…

// Alias the intercept and wait
cy.intercept("GET", "/api").as("get"); cy.wait("@get");        // โœ…

// Use function() for the this form
it("...", function () { expect(this.users).to.have.length(3); }); // โœ…

โŒ Don’t Do This:

// Use an arrow function with this
it("...", () => { expect(this.users).to.have.length(3); }); // undefined // โŒ

// Assume the alias is a snapshot
cy.get("h1").as("heading");
// cy.get("@heading") re-runs the chain, not the stored element   // โŒ

// Alias without retrieving
cy.get("h1").as("heading"); // never used                       // โŒ

Common Pitfalls

PitfallWhy It HappensFix
this.alias undefinedArrow functionUse function ()
Alias not foundTypo or not createdCheck the .as call
Stale elementAlias re-runs the chainRe-query if the DOM changed
Intercept not waitedNo cy.waitWait on the alias

Real-World Examples

1. Subject alias

cy.get('[data-cy="email"]').as("email");

2. Retrieve the subject

cy.get("@email").type("a@b.com");

3. Text alias

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

4. Intercept alias

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

5. Wait on the intercept

cy.wait("@get");

6. Fixture alias

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

7. Retrieve the fixture

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

8. this access

it("...", function () { expect(this.users).to.have.length(3); });

9. beforeEach alias

beforeEach(() => { cy.get("h1").as("heading"); });

10. Shared before alias

before(function () { cy.fixture("u.json").as("users"); });

Visual

The Alias Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  cy.get(sel) โ†’ subject                                  โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  .as("name") โ†’ stored on the test context               โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  cy.get("@name") โ†’ resolves the aliased chain           โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  The commands operate on the result                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Three Sources

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SUBJECT            cy.get(sel).as("el")                โ”‚
โ”‚  INTERCEPT          cy.intercept(...).as("req")         โ”‚
โ”‚  FIXTURE            cy.fixture("f").as("data")          โ”‚
โ”‚                                                         โ”‚
โ”‚  cy.get("@el")      cy.wait("@req")  cy.get("@data")    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The this Form

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  beforeEach(() => {                                     โ”‚
โ”‚    cy.fixture("users.json").as("users");                โ”‚
โ”‚  });                                                    โ”‚
โ”‚                                                         โ”‚
โ”‚  it("...", function () {     โ—„โ”€โ”€ function, not arrow    โ”‚
โ”‚    expect(this.users).to.have.length(3);                โ”‚
โ”‚  });                                                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Reusable Selector

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  beforeEach(() => {                                     โ”‚
โ”‚    cy.visit("/dashboard");                              โ”‚
โ”‚    cy.get("h1").as("heading");                          โ”‚
โ”‚  });                                                    โ”‚
โ”‚                                                         โ”‚
โ”‚  it("checks", () => {                                   โ”‚
โ”‚    cy.get("@heading").should("contain", "Dashboard");   โ”‚
โ”‚  });                                                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Alias syntax.as("name")
Retrieve subjectcy.get("@name")
Wait on interceptcy.wait("@name")
Direct accessthis.name (with function ())
SourcesSubject, intercept, fixture
ScopeTest context, per test

Key takeaways:

  • An alias stores a value that crosses the command queue. .as("name") names the previous command’s subject, and cy.get("@name") retrieves it later, which is how the test keeps a reference without nesting every command in a .then().
  • The alias re-runs the command chain when retrieved. cy.get("h1").as("heading") and cy.get("@heading") re-query the h1 and re-extract the text, which is why an alias is a lazy reference rather than a snapshot.
  • The intercept alias is the wait target. cy.intercept(...).as("getUsers") and cy.wait("@getUsers") block until the request completes, which is the network synchronization point.
  • The this form requires a function (). The alias is bound to the test context, and an arrow function does not have the this that the alias is attached to.
  • The alias is the reusable selector. A beforeEach that aliases the page’s elements gives every test in the block a named reference, which is the Cypress equivalent of a page object’s element getter.

Remember: An alias is a name for a value that the queue has produced. Use it to keep a reference to an element, a request, or a fixture that the test needs later. Retrieve it with cy.get("@name"), wait on the intercept with cy.wait("@name"), and use the this.name form only with a function (). The alias is resolved at the point of use, not the point of definition, which is the detail that makes it work with the queue.

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!