Cypress 13 ๐ฒ Aliases โ cy.as() and Reusable Selectors or Requests
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
| Source | Example |
|---|---|
| DOM subject | cy.get(sel).as("el") |
| Extracted value | cy.get(sel).invoke("text").as("text") |
| Intercept | cy.intercept(...).as("req") |
| Fixture | cy.fixture("f.json").as("data") |
Retrieval
| Form | Use |
|---|---|
cy.get("@name") | Retrieve the alias |
cy.wait("@name") | Wait on an intercept |
this.name | Direct access (requires function ()) |
Function Type
| Test Function | this 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
this.alias undefined | Arrow function | Use function () |
| Alias not found | Typo or not created | Check the .as call |
| Stale element | Alias re-runs the chain | Re-query if the DOM changed |
| Intercept not waited | No cy.wait | Wait 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
| Item | Value |
|---|---|
| Alias syntax | .as("name") |
| Retrieve subject | cy.get("@name") |
| Wait on intercept | cy.wait("@name") |
| Direct access | this.name (with function ()) |
| Sources | Subject, intercept, fixture |
| Scope | Test context, per test |
Key takeaways:
- An alias stores a value that crosses the command queue.
.as("name")names the previous command’s subject, andcy.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")andcy.get("@heading")re-query theh1and 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")andcy.wait("@getUsers")block until the request completes, which is the network synchronization point. - The
thisform requires afunction (). The alias is bound to the test context, and an arrow function does not have thethisthat the alias is attached to. - The alias is the reusable selector. A
beforeEachthat 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.
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!