How do you create a custom command and type it in TypeScript?
A custom command is registered with Cypress.Commands.add in the support file, and its type is added to the Cypress.Chainable interface for TypeScript. The body calls ordinary cy commands that go into the queue, so the command does not return a value synchronously or mix with async/await. Registration and type live separately: the file needs export {}, and tsconfig must include the support folder with the cypress types.
Cypress · Patterns and data
The same cy.get('[data-cy=…]') in fifty tests. Where do you hide it so TypeScript still autocompletes?
In a suite of fifty tests every test opens with five lines of login and the [data-cy="…"] selector is typed by hand hundreds of times. When the team renames the attribute, everything needs editing. A custom command gathers this code in one place and adds a new action to cy. This lesson covers how to register one, how to describe its type so the editor and tsc know about it, and where custom commands do harm.
How it works and why. Cypress does not run cy.get() immediately: every call puts a command in a queue, and the runner then walks the queue one by one, waiting and retrying. Cypress.Commands.add(name, fn) adds one more name to the same mechanism: inside fn you call ordinary cy commands, they join the queue too, and the result of the last one becomes the result of the new command. That is why a command does not return a value synchronously and does not use async/await: it describes what to enqueue.
There is a second half: types. The command exists at runtime, but cy.getByCy is unknown to the compiler until you extend the Cypress.Chainable interface (declaration merging). Both halves live in support files that Cypress loads before every spec (cypress/support/e2e.ts imports ./commands).
Three steps to make a command work
Example: from repetition to a command. Before: every test repeats the same login through the form. Here and below we assume the app sets a session cookie after POST /api/auth/login.
beforeEach(() => {
cy.visit('/login');
cy.get('[data-cy="email"]').type('anna@example.com');
cy.get('[data-cy="password"]').type('secret', { log: false });
cy.get('[data-cy="submit"]').click();
cy.url().should('include', '/dashboard');
});
After: two commands in commands.ts and the type declarations in the same file. TypeScript treats a file without import/export as a script, and declare global is only allowed in a module, so the export {} line is required.
// cypress/support/commands.ts
Cypress.Commands.add('getByCy', (id: string) => {
return cy.get('[data-cy="' + id + '"]');
});
Cypress.Commands.add('login', (email: string, password: string) => {
cy.session(email, () => {
cy.request('POST', '/api/auth/login', { email, password });
});
});
declare global {
namespace Cypress {
interface Chainable {
getByCy(id: string): Chainable<JQuery<HTMLElement>>;
login(email: string, password: string): Chainable<void>;
}
}
}
export {};
// the test
beforeEach(() => cy.login('anna@example.com', 'secret'));
it('shows the dashboard', () => {
cy.visit('/dashboard');
cy.getByCy('balance').should('be.visible');
});
Why this way. cy.session() caches cookies and storage after the first login and restores them in later tests, so the command is not only shorter but faster. getByCy returns the cy.get(...) chain, so .should() and .click() continue it as usual. The result type Chainable<JQuery<HTMLElement>> mirrors what cy.get itself returns: write Chainable<void> and the following calls lose their suggestions. For the editor to see the types, cypress/tsconfig.json needs "types": ["cypress"] and must include the support folder.
Related forms. A child command receives the previous result as subject when you pass the prevSubject option. An existing command can be wrapped with Cypress.Commands.overwrite, for example to add default options to visit.
Cypress.Commands.add('findByCy', { prevSubject: 'element' }, (subject, id: string) => {
return cy.wrap(subject).find('[data-cy="' + id + '"]');
});
// in Chainable:
// findByCy(id: string): Chainable<JQuery<HTMLElement>>;
cy.getByCy('order-list').findByCy('row-1').click();
Limits and alternatives. A command is optional. A plain function that returns the chain works the same way, and the editor offers "go to definition" without type tricks. Commands pay off where you want an action "inside cy": login, getByCy. Inside a command you cannot mix async/await with the Cypress queue, and assertions buried in a command make a test unreadable. Playwright has no custom commands: fixtures from test.extend<MyFixtures>(), helpers and Page Object methods play their role.
Common mistakes.
- Forgetting
export {}or the import insupport/e2e.ts: the type is "not found" or the command is missing at runtime. - Declaring the type but not registering the command:
tscis silent and the test fails with "cy.login is not a function". - Writing
const el = cy.getByCy('x')and usingelas a value: it is a queued step, not an element. - A ten-line command with conditions and assertions: the test looks simple and the logic is hidden.
Check yourself
The cy.login() command is registered, but tsc says "Property 'login' does not exist on type Chainable". What do you check?
Answer
Whether the method is declared in interface Chainable inside declare global { namespace Cypress }, whether the file has export {} (otherwise it is not a module), and whether the Cypress tsconfig includes the support folder with types: ["cypress"]. Registration in Commands.add does not affect types.
Why can't a command contain const res = await cy.request(...)?
Answer
cy.request returns not a Promise but a description of a step in the Cypress queue. await will not wait for it to run. You take the result in .then() or through an alias.