1. Home
  2. Blog
  3. Test Automation

Test Automation

Cypress Tutorial for Beginners: Write Your First End-to-End Test

Go from an empty folder to a running browser test. This Cypress tutorial covers installation, your first test, stable selectors, smart waiting, API stubbing and headless runs.

8 min read
Cypress tutorial for beginners: write your first end-to-end test

Key takeaways

  • Cypress is a JavaScript end-to-end testing tool that runs inside the browser and retries assertions automatically.
  • Install it with npm install cypress --save-dev and open it with npx cypress open.
  • Prefer data-cy attributes over CSS classes, and never use fixed cy.wait(5000) sleeps.
  • Use cy.intercept to control API responses and npx cypress run to run headless in CI.

Selenium made browser testing possible, but many teams find it slow to set up and flaky to maintain. Cypress was built to make the same job simpler for web developers: one install, a visual test runner and automatic waiting.

This Cypress tutorial for beginners assumes you know basic JavaScript. If not, start with our JavaScript tutorial for beginners.

What Cypress is

Cypress is an open-source end-to-end test tool for web apps. Your tests are written in JavaScript or TypeScript and run in the same browser as your app, so Cypress can watch every network call and DOM change. It retries many commands and assertions until they pass or a timeout is reached, which removes most manual waiting.

Install and set up

You need Node.js. Then create a project and add Cypress.

mkdir cypress-demo && cd cypress-demo
npm init -y
npm install cypress --save-dev
npx cypress open

The first launch opens the Cypress app. Choose E2E Testing, pick a browser and let it create the default files. You get a cypress.config.js file and a cypress/ folder with e2e for your specs and support for shared commands. Test files end in .cy.js.

Your first test

Create cypress/e2e/first.cy.js. This test uses Cypress’s own practice site, so it works anywhere.

describe("Cypress practice site", () => {
  it("opens the Actions page and types in a field", () => {
    cy.visit("https://example.cypress.io");
    cy.contains("type").click();
    cy.url().should("include", "/commands/actions");
    cy.get(".action-email")
      .type("hello@stackquora.com")
      .should("have.value", "hello@stackquora.com");
  });
});

Read it as a story: visit the site, click the link that contains the word “type”, check that the URL changed, then type into the email field and check its value. describe groups tests and it defines one test. Click the spec in the Cypress app and watch it run, with a snapshot for every step.

Choosing stable selectors

A test is only as stable as its selectors. CSS classes change for styling reasons, so tests that depend on them break. Add dedicated test attributes to your HTML.

<button data-cy="submit-order">Place order</button>

cy.get("[data-cy=submit-order]").click();
Selector Stability
[data-cy=submit-order] Best: exists only for tests
Visible text via cy.contains() Good for user-facing labels
#order-form (an ID) Fair: can change with refactors
.btn.btn-primary.large Poor: tied to styling

Waiting the right way

Because Cypress retries, you almost never need a sleep. Write the assertion and let it wait.

// Bad: always waits 5 seconds, still can fail
cy.wait(5000);

// Good: retries until the element appears (default 4 seconds)
cy.get("[data-cy=result]").should("be.visible");

Compare this with explicit waits in older tools in our guide to Selenium waits. For slow pages, raise the timeout on one command, for example cy.get(".chart", { timeout: 10000 }).

Stubbing API calls with cy.intercept

End-to-end tests become fast and reliable when you control the data. cy.intercept catches a request and can answer it with a fixture file.

cy.intercept("GET", "/api/users", { fixture: "users.json" }).as("getUsers");
cy.visit("/users");
cy.wait("@getUsers");
cy.get("[data-cy=user-row]").should("have.length", 3);

Here cy.wait("@getUsers") waits for the named request, which is the correct kind of wait. Put users.json in cypress/fixtures. Check the real API separately with API testing with Postman.

Run headless and in CI

Set a base URL once so tests can use short paths.

// cypress.config.js
const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: { baseUrl: "http://localhost:3000" },
});

Then run everything without the UI.

npx cypress run
npx cypress run --browser chrome --spec "cypress/e2e/first.cy.js"

cypress run exits with a failure code when a test fails, so a CI server can stop the build. See how to wire it up in our GitHub Actions CI/CD guide.

Limits to know before you commit

  • Tests are written in JavaScript or TypeScript only.
  • Cypress controls one browser tab per test and has constraints with multiple origins and multiple windows.
  • It is aimed at web apps, not native mobile apps.

If these matter to you, compare tools in Playwright vs Cypress, and follow our end-to-end testing best practices to keep your suite stable.

Final thoughts

Start with one valuable user journey, such as signing in or checking out. Use data-cy selectors, let Cypress retry, stub the slow parts and run it on every pull request.

Frequently asked questions

Is Cypress good for beginners?

Yes. Setup is a single npm install, the test runner shows each step visually, and automatic waiting removes a lot of the flakiness beginners meet in other tools.

Which language does Cypress use?

Cypress tests are written in JavaScript or TypeScript.

Do I need to install a browser driver for Cypress?

No. Cypress works with the browsers installed on your computer, and includes Electron, so there is no separate driver to download.

What is the difference between cypress open and cypress run?

cypress open starts the interactive app for writing and debugging tests. cypress run runs tests headless in the terminal, which is what you use in CI.

Can Cypress test APIs?

Yes. cy.request sends HTTP requests directly, and cy.intercept lets you spy on or stub the requests your app makes.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →