/// <reference types="cypress" />
// cypress/support/commands.ts
Cypress.Commands.add('login', (username: string, password: string) => {
cy.get('[data-cy=username]').clear().type(username);
cy.get('[data-cy=password]').clear().type(password);
cy.get('[data-cy=login-button]').click();
});
// cypress/support/index.d.ts
// This file adds TypeScript support for the custom command
/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable {
/**
* Custom command to login
* @example cy.login('user1', 'pass123')
*/
login(username: string, password: string): Chainable<void>;
}
}
// cypress/e2e/login.cy.ts
describe('Login Test with Custom Command', () => {
beforeEach(() => {
cy.visit('/login');
});
it('logs in using custom command and verifies dashboard URL', () => {
cy.login('testuser', 'TestPass123!');
cy.url().should('include', '/dashboard');
});
});The code defines a custom Cypress command named login in commands.ts. It uses cy.get with data-cy attributes to find username, password fields, and the login button, then performs typing and clicking.
In index.d.ts, the Cypress namespace is extended to add TypeScript support for the login command. This allows TypeScript to recognize cy.login() with proper parameter types.
The test file login.cy.ts visits the login page, uses the custom login command with sample credentials, and asserts that the URL contains /dashboard after login.
This setup ensures type safety, code reuse, and clear test steps.