| | |

Cypress 14 ๐ŸŒฒ Custom Commands โ€” Cypress.Commands.add and Reuse Patterns

โฑ๏ธ Estimated read: 10 min | |

A custom command is a named function that is added to the cy chain. Cypress.Commands.add("name", fn) registers it, and cy.name(...) calls it with the same queue semantics as a built-in command. The custom command is the mechanism for the repeated sequenceโ€”a login flow, a form fill, an API seedโ€”that would otherwise be copied into every test, and it is the Cypress equivalent of a helper function with the chain’s automatic waiting and logging.

This chapter covers the Cypress.Commands.add API, the two forms of the custom command (parent and child), and the TypeScript declaration that makes the custom command visible to the type system. The sections that follow walk through the registration, the subject-chaining child command, and the logging and TypeScript integration that make a custom command a first-class part of the test.

Key point: Cypress.Commands.add("name", fn) registers a parent command called as cy.name(...); Cypress.Commands.add("name", { prevSubject: true }, fn) registers a child command called as cy.get(sel).name(...), and the TypeScript Chainable declaration is what makes either visible to the compiler.


a. The parent command and the registration

A parent command is called as cy.name(...). It does not receive a subject, and it starts a new chain. The login, the API seed, and the fixture setup are the parent commands.

// cypress/support/commands.js
Cypress.Commands.add("login", (email, password) => {
  cy.visit("/login");
  cy.get('[data-cy="email"]').type(email);
  cy.get('[data-cy="password"]').type(password);
  cy.get('[data-cy="submit"]').click();
  cy.url().should("include", "/dashboard");
});

The command is registered in the support file, which runs before every spec. The cypress/support/commands.js is the default location, and the supportFile config option points at it. The command is available in every test after the support file runs, without an import.

The custom command is a function that enqueues cy commands. The test calls cy.login("user@example.com", "password"), and the commands inside the custom command run in the queue in the order they were enqueued. The cy.url().should(...) at the end is the assertion that the login completed, which makes the command self-verifying.

The custom command can return a value that becomes the subject for the next command. A cy.createUser(...) that returns the created user’s id is the pattern for a command whose result the test needs.

Cypress.Commands.add("createUser", (name) => {
  return cy.request("POST", "/api/users", { name }).then((response) => {
    return response.body.id;
  });
});

// Usage
cy.createUser("Ana").then((id) => {
  cy.visit(`/users/${id}`);
});

The return inside the .then() becomes the subject of the next command, which is how a custom command produces a value for the test. The cy.wrap() is the explicit form when the value is not already a chainable.


b. The child command and prevSubject

A child command is called on a subject: cy.get(sel).name(...). It receives the previous command’s subject as its first argument, and the { prevSubject: true } option is what tells Cypress the command expects one.

Cypress.Commands.add(
  "fillForm",
  { prevSubject: true },
  (subject, data) => {
    cy.wrap(subject).find('[data-cy="name"]').type(data.name);
    cy.wrap(subject).find('[data-cy="email"]').type(data.email);
    return subject; // pass the subject to the next command
  }
);

// Usage
cy.get("form").fillForm({ name: "Ana", email: "ana@example.com" });

The prevSubject option has three values. true requires a subject, false forbids one, and "optional" allows the command to be called with or without a subject. The true value is the common case for a command that operates on an element, and the "optional" value is for a command that can work both ways.

The child command’s return value is the next subject. A command that does not return anything passes the subject it received, which is the behavior for a command that only performs side effects. A command that returns a different valueโ€”a text, a countโ€”passes that value to the next command.

Cypress.Commands.add(
  "textTrimmed",
  { prevSubject: true },
  (subject) => subject.text().trim()
);

// Usage
cy.get("h1").textTrimmed().should("eq", "Welcome");

The subject.text().trim() returns a string, which becomes the subject of the should. The child command is the way to write a reusable extraction that composes with the chain.


c. The TypeScript declaration and the logging

A custom command is invisible to the TypeScript compiler unless the Chainable interface is augmented. The cypress/support/commands.ts file declares the interface, and the cy.login(...) call is then type-checked.

// cypress/support/commands.ts
declare global {
  namespace Cypress {
    interface Chainable {
      login(email: string, password: string): Chainable<void>;
      createUser(name: string): Chainable<string>;
    }
  }
}

Cypress.Commands.add("login", (email: string, password: string) => {
  // ...
});

The Chainable augmentation is the contract. It names the command, the arguments, and the return type, and the compiler enforces the shape at the call site. A project that uses TypeScript needs the augmentation for every custom command, and the cypress/support/e2e.ts file is the place it lives.

The Cypress.log is the logging. A custom command without a log is a black box in the Command Log, and a command with a log has the same visibility as a built-in one.

Cypress.Commands.add("login", (email, password) => {
  const log = Cypress.log({
    name: "login",
    message: `${email}`,
    autoEnd: false,
  });

  cy.visit("/login");
  cy.get('[data-cy="email"]').type(email);
  cy.get('[data-cy="password"]').type(password);
  cy.get('[data-cy="submit"]').click();
  cy.url().should("include", "/dashboard").then(() => {
    log.end();
  });
});

The autoEnd: false is required because the command’s cy calls are asynchronous. The log.end() is called in a .then() after the last assertion, which is the point where the command has actually completed.

The Cypress.Commands.overwrite is the way to modify a built-in command. A project that wants every cy.visit to set a header, or every cy.type to log the value, overwrites the built-in command and calls the original.

Cypress.Commands.overwrite("visit", (originalFn, url, options) => {
  return originalFn(url, {
    ...options,
    headers: { "x-test": "true", ...options?.headers },
  });
});

The overwrite receives the original function as its first argument, which is the mechanism for adding behavior without losing the original. It is a heavier tool than the add, and it is the right choice only when the behavior must apply to every call of the built-in command.


Complete Example Session

// ============================================
// PART 1: THE PARENT COMMAND
// ============================================
// cypress/support/commands.ts
Cypress.Commands.add("login", (email: string, password: string) => {
  cy.session([email, password], () => {
    cy.visit("/login");
    cy.get('[data-cy="email"]').type(email);
    cy.get('[data-cy="password"]').type(password);
    cy.get('[data-cy="submit"]').click();
    cy.url().should("include", "/dashboard");
  });
});

// Usage
cy.login("user@example.com", "password123");

// ============================================
// PART 2: THE CHILD COMMAND
// ============================================
Cypress.Commands.add(
  "fillForm",
  { prevSubject: true },
  (subject: JQuery<HTMLElement>, data: { name: string; email: string }) => {
    cy.wrap(subject).find('[data-cy="name"]').type(data.name);
    cy.wrap(subject).find('[data-cy="email"]').type(data.email);
    return subject;
  }
);

// Usage
cy.get("form").fillForm({ name: "Ana", email: "ana@example.com" });

// ============================================
// PART 3: THE TYPESCRIPT DECLARATION
// ============================================
declare global {
  namespace Cypress {
    interface Chainable {
      login(email: string, password: string): Chainable<void>;
      fillForm(data: { name: string; email: string }): Chainable<JQuery<HTMLElement>>;
    }
  }
}

// ============================================
// PART 4: THE LOG
// ============================================
Cypress.Commands.add("login", (email, password) => {
  const log = Cypress.log({ name: "login", message: email, autoEnd: false });
  cy.session([email, password], () => { /* ... */ }).then(() => log.end());
});

The parts covered the parent command, the child command, the TypeScript declaration, and the log.


Quick Reference

Registration

FormCall
Parentcy.name(...)
Childcy.get(sel).name(...)
OverwriteCypress.Commands.overwrite("visit", fn)

prevSubject

ValueBehavior
trueRequires a subject
falseForbids a subject
"optional"Allows either

TypeScript

ItemDetail
Augmentationinterface Chainable
Locationcypress/support/commands.ts
Return typeChainable<T>

Best Practices

โœ… Do This:

// Register the command in the support file
Cypress.Commands.add("login", (email, password) => { ... });  // โœ…

// Return the subject from a child command
return subject;                                                // โœ…

// Declare the command in the Chainable interface
interface Chainable { login(email: string, password: string): Chainable<void>; } // โœ…

โŒ Don’t Do This:

// Use an arrow function for a command that needs this
Cypress.Commands.add("x", () => { this; }); // this is not the context // โŒ

// Forget the prevSubject for a child command
Cypress.Commands.add("fill", (data) => { ... }); // no subject        // โŒ

// Use autoEnd false without log.end()
Cypress.log({ autoEnd: false }); // the log never closes             // โŒ

Common Pitfalls

PitfallWhy It HappensFix
TypeScript error on cy.loginNo Chainable augmentationDeclare the interface
Command not availableSupport file not loadedCheck supportFile
Child command does not chainNo prevSubjectAdd the option
Log never closesautoEnd: false without log.end()Call log.end()

Real-World Examples

1. Parent login

Cypress.Commands.add("login", (email, password) => { ... });

2. Child fill

Cypress.Commands.add("fill", { prevSubject: true }, (subject, data) => { ... });

3. Return a value

Cypress.Commands.add("createUser", (name) => cy.request(...).then((r) => r.body.id));

4. TypeScript declaration

interface Chainable { login(e: string, p: string): Chainable<void>; }

5. Overwrite

Cypress.Commands.overwrite("visit", (original, url, opts) => original(url, opts));

6. Log

Cypress.log({ name: "login", message: email, autoEnd: false });

7. cy.session in a command

cy.session([email, password], () => { ... });

8. Optional subject

Cypress.Commands.add("x", { prevSubject: "optional" }, (subject) => { ... });

9. Return the subject

return subject;

10. Assert inside the command

cy.url().should("include", "/dashboard");

Visual

Parent vs Child

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  PARENT                                                 โ”‚
โ”‚  cy.login(email, password)                              โ”‚
โ”‚    โ†’ starts a new chain                                 โ”‚
โ”‚                                                         โ”‚
โ”‚  CHILD                                                  โ”‚
โ”‚  cy.get("form").fillForm(data)                          โ”‚
โ”‚    โ†’ receives the form as the subject                   โ”‚
โ”‚    โ†’ returns the subject to the next command            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The TypeScript Declaration

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  declare global {                                       โ”‚
โ”‚    namespace Cypress {                                  โ”‚
โ”‚      interface Chainable {                              โ”‚
โ”‚        login(email: string, password: string): Chainable<void>;โ”‚
โ”‚      }                                                  โ”‚
โ”‚    }                                                    โ”‚
โ”‚  }                                                      โ”‚
โ”‚                                                         โ”‚
โ”‚  Without this, cy.login is a type error.                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Log

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  const log = Cypress.log({ autoEnd: false });           โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  cy commands run                                        โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  .then(() => log.end())                                 โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  The log closes when the command actually completes     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
RegisterCypress.Commands.add("name", fn)
Parent callcy.name(...)
Child callcy.get(sel).name(...)
Child option{ prevSubject: true }
TypeScriptinterface Chainable
LogCypress.log({ autoEnd: false })
OverwriteCypress.Commands.overwrite

Key takeaways:

  • A custom command is registered with Cypress.Commands.add. The parent command is called as cy.name(...), and the child command is called on a subject as cy.get(sel).name(...).
  • The prevSubject option determines the command type. true requires a subject, false forbids one, and "optional" allows either. The child command receives the subject as its first argument and returns the next subject.
  • The TypeScript declaration is required for a typed project. The Chainable interface augmentation names the command and its signature, and without it the cy.name call is a type error.
  • The Cypress.log gives the command visibility. A command without a log is a black box in the Command Log, and the autoEnd: false plus log.end() pattern keeps the log open until the async work completes.
  • The overwrite is for modifying a built-in command. It receives the original function and calls it, which is the mechanism for adding behavior to every cy.visit or cy.type without losing the original.

Remember: A custom command is a named step in the chain. The parent command starts a chain, the child command continues one, and the prevSubject option declares which. Declare the command in the Chainable interface, register it in the support file, and log it if the test needs to see what it did. The command is the reuse mechanism that keeps a test readable: one cy.login(...) instead of five cy.get(...).type(...) calls repeated in every file.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!