Skip to content

Cypress - Aliases

Aliases in Cypress, created with the .as() command, are a powerful feature for writing clearer, more maintainable, and robust tests. They allow you to reference and reuse subjects like DOM elements, network requests, fixtures, and other values later in your tests.

Aliases can be used to share data or subjects across different test steps or hooks (like beforeEach).

1. Aliasing Primitives and Objects (Mocha Context)

Section titled “1. Aliasing Primitives and Objects (Mocha Context)”

For simple values or objects not managed by Cypress’s command queue (like raw strings or numbers), you can alias them and access them via Mocha’s shared this context. This requires using function declarations (function() { ... }) for your tests and hooks, not arrow functions, to ensure this refers to the Mocha context.

describe('User Profile', function() {
beforeEach(function() {
cy.wrap({ name: 'Alice', role: 'admin' }).as('userData');
cy.wrap('main-content').as('contentId');
});
it('should display user name from aliased data', function() {
// Accessing alias via Mocha's 'this' context
expect(this.userData.name).to.equal('Alice');
cy.log(`Content ID is: ${this.contentId}`);
});
});

Note: Properties on this are reset after each test.

2. Aliasing Cypress Subjects (DOM Elements, Intercepts, Requests)

Section titled “2. Aliasing Cypress Subjects (DOM Elements, Intercepts, Requests)”

When you alias subjects that Cypress yields (like DOM elements from cy.get(), network intercepts from cy.intercept(), or request results from cy.request()), you should access them using cy.get('@aliasName'). This is the more common and recommended way to work with aliases for Cypress-managed objects, as it respects Cypress’s retry-ability.

Reuse DOM element selections without re-querying the DOM unnecessarily. Cypress will re-run the query for cy.get('@aliasName') if the element is not immediately found or is detached, providing resilience.

describe('DOM Element Aliasing', () => {
beforeEach(() => {
// Example: <table id='users-table'><tbody><tr><td>UserA</td><td>Active</td></tr></tbody></table>
cy.visit('/path-to-your-page-with-table.html'); // Replace with your page
// Alias the collection of table data cells (td) in the first row
cy.get('#users-table tbody tr:first-child td').as('firstRowCells');
});
it('should interact with aliased cells', () => {
cy.get('@firstRowCells').eq(0).should('contain.text', 'UserA');
cy.get('@firstRowCells').eq(1).click(); // Example: click the status cell
});
});

Using cy.get('@aliasName') ensures that Cypress interacts with the most up-to-date state of the element.

Aliasing Network Intercepts (formerly Routes)

Section titled “Aliasing Network Intercepts (formerly Routes)”

cy.intercept() is used to manage network requests and responses. Aliasing an intercept allows you to wait for it and assert on its properties.

describe('Network Intercept Aliasing', () => {
it('should wait for a POST request and verify its body', () => {
// Intercept POST requests to '/users' and alias it as 'createUser'
cy.intercept('POST', '/api/users').as('createUser');
// Trigger the action that makes the POST request (e.g., submitting a form)
cy.get('#user-form-name').type('Test User');
cy.get('#user-form-submit').click();
// Wait for the aliased 'createUser' intercept to complete
cy.wait('@createUser').then((interception) => {
// Assert on the request body
expect(interception.request.body).to.have.property('name', 'Test User');
// Assert on the response status code
expect(interception.response.statusCode).to.equal(201);
});
cy.contains('User successfully added!').should('be.visible');
});
});

You can alias the result of a cy.request() to use its properties (like status, body, headers) later.

describe('cy.request() Aliasing', () => {
it('should fetch comments and verify the response', () => {
cy.request('https://jsonplaceholder.typicode.com/comments?postId=1').as('postComments');
// Other test steps can occur here
cy.get('@postComments').should((response) => {
expect(response.status).to.equal(200);
expect(response.body).to.be.an('array').and.not.be.empty;
response.body.forEach(comment => {
expect(comment).to.have.property('postId', 1);
});
});
});
});
  • Readability: Makes tests easier to understand by giving meaningful names to complex subjects.
  • Reusability: Allows you to define a subject once and refer to it multiple times.
  • Resilience (for DOM elements): When using cy.get('@aliasName') for DOM elements, Cypress re-queries the DOM, helping to avoid stale element references.
  • Synchronization: Essential for managing asynchronous operations like network requests (cy.wait('@aliasName')).

Best Practice: Prefer cy.get('@aliasName') for accessing Cypress-yielded subjects. Use this.aliasName (with function()) primarily for simple data stored on Mocha’s context when needed.