Manuals / Cypress / Ch 4

B · CoreIntermediate55 min read

4. Custom commands & reusable flows

Cypress · 48 pages source format

DRY with intent. Custom commands wrap repeated flows without hiding too much. Keep parameters visible in specs.

What you'll learn

  • cy.commands.add
  • Support file
  • Type definitions for IDE

login custom command

Wrap auth in cy.login(user, pass). Specs stay readable; implementation lives in cypress/support/commands.js.

Cypress.Commands.add("login", (username, password) => {
  cy.visit("/");
  cy.get("[data-test=username]").type(username);
  cy.get("[data-test=password]").type(password);
  cy.get("[data-test=login-button]").click();
});

Do this now

Create cy.login and use it in two specs.

Clear?

Command boundaries

Do not hide assertions inside commands unless they are universal (e.g. login always lands on inventory).

Do this now

Review commands — each should do one thing. Split overloaded commands.

Clear?

Fixtures for test data

cy.fixture("users.json") loads static data. Combine with dynamic ids for isolation.

Do this now

Create fixtures/users.json with standard_user, locked_out_user, problem_user.

Clear?

beforeEach hygiene

Reset state before each test. cy.visit or session restore — never assume prior test left clean state.

Do this now

Add beforeEach that visits baseUrl or restores session. Verify tests pass in isolation.

Clear?

Checklist