Custom commands help you reuse test steps easily. Using TypeScript makes sure your commands are checked for mistakes before running tests.
0
0
TypeScript support for custom commands in Cypress
Introduction
You want to create a shortcut for a repeated test action, like logging in.
You want to add new commands to Cypress that fit your app's needs.
You want your custom commands to have clear types and auto-complete in your editor.
You want to avoid mistakes by checking command inputs and outputs before running tests.
Syntax
Cypress
declare namespace Cypress {
interface Chainable {
customCommand(param: string): Chainable<Element>;
}
}
Cypress.Commands.add('customCommand', (param) => {
// command implementation
});Use declare namespace Cypress to add types for your commands.
Define your command inside interface Chainable with input and output types.
Examples
This example adds a
login command with typed email and password parameters.Cypress
declare namespace Cypress {
interface Chainable {
login(email: string, password: string): Chainable<Element>;
}
}
Cypress.Commands.add('login', (email, password) => {
cy.get('#email').type(email);
cy.get('#password').type(password);
cy.get('button[type=submit]').click();
});This example adds a
selectItem command to click an item by name.Cypress
declare namespace Cypress {
interface Chainable {
selectItem(itemName: string): Chainable<Element>;
}
}
Cypress.Commands.add('selectItem', (itemName) => {
cy.contains(itemName).click();
});Sample Program
This test adds a greet command that logs a greeting message. The test calls cy.greet('Alice') and you will see the greeting in the test log.
Cypress
/// <reference types="cypress" /> declare namespace Cypress { interface Chainable { greet(name: string): Chainable<Element>; } } Cypress.Commands.add('greet', (name) => { cy.log(`Hello, ${name}!`); }); describe('Custom Command Test', () => { it('uses the greet command', () => { cy.greet('Alice'); }); });
OutputSuccess
Important Notes
Always add /// <reference types="cypress" /> at the top for TypeScript support.
Put your type declarations in a cypress/support/index.d.ts or similar file.
Use Chainable<Element> as the return type for commands that continue Cypress chaining.
Summary
Custom commands let you reuse test steps easily.
TypeScript support helps catch errors early and improves editor help.
Declare your commands in the Cypress.Chainable interface for typing.