Cypress 14 ๐ฒ Custom Commands โ Cypress.Commands.add and Reuse Patterns
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
| Form | Call |
|---|---|
| Parent | cy.name(...) |
| Child | cy.get(sel).name(...) |
| Overwrite | Cypress.Commands.overwrite("visit", fn) |
prevSubject
| Value | Behavior |
|---|---|
true | Requires a subject |
false | Forbids a subject |
"optional" | Allows either |
TypeScript
| Item | Detail |
|---|---|
| Augmentation | interface Chainable |
| Location | cypress/support/commands.ts |
| Return type | Chainable<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
| Pitfall | Why It Happens | Fix |
|---|---|---|
TypeScript error on cy.login | No Chainable augmentation | Declare the interface |
| Command not available | Support file not loaded | Check supportFile |
| Child command does not chain | No prevSubject | Add the option |
| Log never closes | autoEnd: 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
| Item | Value |
|---|---|
| Register | Cypress.Commands.add("name", fn) |
| Parent call | cy.name(...) |
| Child call | cy.get(sel).name(...) |
| Child option | { prevSubject: true } |
| TypeScript | interface Chainable |
| Log | Cypress.log({ autoEnd: false }) |
| Overwrite | Cypress.Commands.overwrite |
Key takeaways:
- A custom command is registered with
Cypress.Commands.add. The parent command is called ascy.name(...), and the child command is called on a subject ascy.get(sel).name(...). - The
prevSubjectoption determines the command type.truerequires a subject,falseforbids 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
Chainableinterface augmentation names the command and its signature, and without it thecy.namecall is a type error. - The
Cypress.loggives the command visibility. A command without a log is a black box in the Command Log, and theautoEnd: falsepluslog.end()pattern keeps the log open until the async work completes. - The
overwriteis for modifying a built-in command. It receives the original function and calls it, which is the mechanism for adding behavior to everycy.visitorcy.typewithout 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.
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!