← Back to Cypress Mastery
Basic18 min read

Cypress Basics

Install Cypress, write your first E2E test, and run tests in interactive or headless mode.

Installation and Project Setup

Install Cypress as a dev dependency and open the Cypress app to scaffold cypress/e2e and support files. Cypress bundles its own browser versions for consistent runs.

Configure baseUrl in cypress.config.ts so cy.visit("/path") resolves against your dev or preview server. Start the application before running tests locally or in CI.

  • Use npx cypress open for interactive Test Runner
  • Use npx cypress run for headless CI execution
  • Place support/e2e.ts for global hooks and custom commands
npm install --save-dev cypress

// cypress.config.ts
import { defineConfig } from "cypress";

export default defineConfig({
  e2e: {
    baseUrl: "http://localhost:3000",
    specPattern: "cypress/e2e/**/*.cy.{js,ts}",
  },
});

Test Syntax and Structure

Tests use describe and it blocks with callback functions. Cypress chains commands with cy object—each command yields subject to the next. Most commands are asynchronous but do not need await.

Assertions chain directly: cy.get("button").should("be.visible").click(). Implicit waits retry until timeout for DOM stability.

describe("Home page", () => {
  it("displays welcome message", () => {
    cy.visit("/");
    cy.contains("h1", "Welcome").should("be.visible");
  });
});

Running Tests

Interactive mode shows browser, command log, and time travel debugging. Headless mode runs in Electron or configured browsers (chrome, firefox, edge) for CI speed.

Record videos and screenshots on failure via config options—essential artifacts for debugging CI failures remotely.

npx cypress run --browser chrome --spec "cypress/e2e/checkout.cy.ts"

Test Organization

Group specs by user journey or feature—login.cy.ts, checkout.cy.ts. Share selectors and routes in support/commands or page objects without over-abstracting early.

Keep tests independent: each should seed or reset state via API or tasks rather than depending on prior test side effects.

  • One logical user flow per it block; split long flows for clarity
  • Use data-cy attributes for stable selectors agreed with developers
  • Avoid testing third-party sites you do not control

First Test Checklist

Verify app serves on baseUrl, disable uncaught exception failures during spike only (not long term), and confirm test user credentials exist in test environment.

Add smoke spec visiting critical routes in CI before deeper suites run.

// cypress/support/e2e.ts
Cypress.on("uncaught:exception", () => false); // use temporarily only

Get In Touch


Ready to discuss your next project? Drop me a message.