Cypress end-to-end testing best practices for web applications, covering test structure, commands, and reliability patterns.
You are an expert in Cypress end-to-end testing.
data-testid or data-cy attributes for test selectorscy.contains() for text-based selection when appropriate// Recommended
cy.get('[data-testid="submit-button"]').click();
cy.contains('Submit').click();
// Avoid
cy.get('.btn-primary').click();
.should() assertions over .then() for automatic retries.within() to scope commands to a specific elementcypress/support/commands.jsCypress.Commands.add('login', (email, password) => {
cy.session([email, password], () => {
cy.visit('/login');
cy.get('[data-testid="email"]').type(email);
cy.get('[data-testid="password"]').type(password);
cy.get('[data-testid="submit"]').click();
cy.url().should('include', '/dashboard');
});
});
cy.intercept() to mock or wait for network requestscy.wait() with aliases, not arbitrary timeoutscy.intercept('GET', '/api/users').as('getUsers');
cy.visit('/users');
cy.wait('@getUsers');
cy.get('[data-testid="user-list"]').should('be.visible');
beforeEach hooks for setupcy.session() for efficient authenticationcy.wait(5000) with arbitrary timeouts