Test Automation
Test Automation with Cypress
This course teaches test automation for modern web applications using Cypress, a JavaScript-based end-to-end testing tool that runs directly inside the browser alongside the application under test. Learners move from installing Cypress and writing a first test, through selectors, commands and assertions, to handling asynchronous behavior, network requests and fixtures, and finally to organizing a maintainable test suite and wiring it into a continuous integration pipeline. Each section combines conceptual explanation with runnable code examples, practical tips drawn from common real-world test suites, and a list of pitfalls beginners typically hit and how to avoid them. By the end of the course, a learner will be able to set up a Cypress project from scratch, write reliable tests that do not depend on fixed waits, stub network responses, and run the suite automatically on every code change.
Beginner · By the Xtest team · About 29 minutes to read
Introduction
Test automation lets a team run the same checks against a web application over and over, catching regressions long before a person would notice them by hand. Cypress is one of the most widely used tools for this kind of testing because it runs inside the same browser process as the application it is testing, which lets it see everything the page does, from DOM changes to network calls, without the fragile timing problems that plague older browser-automation tools. This course starts from zero: what Cypress is, how its architecture differs from a tool that drives the browser from the outside, and how to install it into a project. From there you will write real tests, select elements reliably, make assertions, deal with asynchronous page behavior and network requests, and organize a growing suite so it stays readable and fast. The final sections cover running your suite in continuous integration so every pull request is checked automatically. Writing and maintaining this kind of test code is one way to automate end-to-end testing; it is worth knowing that it is not the only way. xtest, for example, is a hosted web application for end-to-end testing with AI test agents, where you describe a test in plain English, pick a device, and a test agent carries the test out while you watch it live, which is a different approach from writing and maintaining JavaScript test files yourself. This course, however, focuses entirely on the code-first approach with Cypress, since that remains the most common way teams build automated browser tests today.
Introduction to Test Automation and Cypress
Why Automate Browser Tests
A web application changes constantly: new features, refactors, dependency upgrades. Every change risks breaking something that used to work. Manually clicking through the application after every change does not scale, so teams write automated tests that a computer can run in seconds or minutes, as often as needed.
What Makes Cypress Different
Many older browser-automation tools send commands to the browser from an external process over a network protocol. This works, but it means the test runner is always a step behind what is actually happening in the page, which leads to tests that need manual waits sprinkled through them to avoid flakiness.
Cypress instead runs in the same run loop as your application. The test code executes inside the browser, right alongside your app's JavaScript. This gives Cypress direct access to the DOM, the window object, network requests and the console, without crossing a network boundary for every command. A practical result of this architecture is automatic retrying: when a Cypress command looks for an element or checks an assertion, it retries for a configurable period before failing, instead of failing immediately the first time the element is not yet there.
What a Cypress Project Looks Like
A Cypress project is a Node.js project with the cypress package added as a dependency. Running cypress open launches an interactive Test Runner that shows your application in one pane and the test commands, as they execute, in another, with time-travel snapshots you can click through after a run to see exactly what the DOM looked like at each step. Running cypress run executes the same tests headlessly from the command line, which is what a CI pipeline typically does.
Scope of This Section
By the end of this section you will understand Cypress's architecture well enough to explain why it behaves differently from an external browser driver, you will have Cypress installed in a project, and you will have written and run your first test against a real page.
Cypress Architecture and the Automatic Retry Model
Cypress is built as two parts that work together: a Node.js process that manages the browser, the file system and the test lifecycle, and the test code itself, which runs inside the browser in the same context as the application under test. Because the test code lives inside the browser, it can read the DOM directly, intercept network requests before the application sees them, and react to JavaScript errors thrown by the page, all without the delay and uncertainty of sending commands over a remote protocol.
This architecture is what enables Cypress's built-in retry-ability. Most Cypress commands that query the DOM, such as cy.get() or cy.contains(), do not run once and immediately fail if they do not find a match. Instead, they retry automatically, re-querying the DOM, for a default timeout of four seconds, until the element appears or the timeout is reached. Assertions chained onto a command are retried the same way: a command like cy.get('.spinner').should('not.exist') will keep checking until the spinner disappears or the timeout runs out. This is why idiomatic Cypress tests rarely need explicit sleeps or fixed waits; the framework's retry loop does that waiting for you, and only as long as actually necessary.
Understanding this model matters because it explains both Cypress's strengths and its boundaries. Because everything runs inside one browser tab, Cypress cannot natively drive two browser tabs or two origins open at once in older configurations, and a test cannot step outside the browser to, for example, read a file system path unrelated to the project without a plugin. Knowing where the browser boundary sits will save you time later when a test behaves unexpectedly.
Installing Cypress and Understanding the Project Structure
Cypress is installed as a development dependency of a Node.js project using a package manager such as npm or yarn. Once installed, running the cypress open command for the first time scaffolds a standard folder structure: a cypress/e2e folder for your test files, a cypress/fixtures folder for static test data such as JSON files, a cypress/support folder for reusable commands and global configuration, and a cypress.config.js file at the project root that holds settings like the base URL of the application under test, the default timeout, and the folders Cypress should use.
The cypress.config.js file is where you configure the e2e testing type, set a baseUrl so your tests can use relative paths like cy.visit('/login') instead of a full URL every time, and register any plugins or event listeners your suite needs. Keeping configuration in this one file, rather than scattered across test files, makes it easy for a whole team to share the same setup and for a CI server to run the suite with the same settings a developer uses locally.
A new test file is simply a JavaScript (or TypeScript) file placed in cypress/e2e, ending in .cy.js by default. Cypress automatically discovers and lists every matching file in the Test Runner, so no separate test registration step is required. Spend time getting this structure right early: a suite that mixes test logic, fixtures and reusable commands with no separation becomes hard to maintain as it grows past a handful of files.
npm init -y
npm install cypress --save-dev
npx cypress open
Initializes a Node.js project, installs Cypress as a dev dependency, and launches the interactive Test Runner, which scaffolds the cypress folder structure on first run.
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
defaultCommandTimeout: 6000,
viewportWidth: 1280,
viewportHeight: 720,
setupNodeEvents(on, config) {
// register plugins or event listeners here
},
},
});
A basic cypress.config.js file that sets the application's base URL, raises the default command timeout slightly, and fixes the viewport size so tests run consistently.
describe('Login page', () => {
it('lets a user log in with valid credentials', () => {
cy.visit('/login');
cy.get('[data-testid="email-input"]').type('user@example.com');
cy.get('[data-testid="password-input"]').type('correct-password');
cy.get('[data-testid="submit-button"]').click();
cy.url().should('include', '/dashboard');
cy.contains('Welcome back').should('be.visible');
});
});
A first Cypress test: it visits the login page, fills in the form using data-testid selectors, submits it, and asserts the user lands on the dashboard with a welcome message.
Tips
- Prefer data-testid or similar dedicated test attributes over CSS classes or text content for selectors, since class names and copy change far more often than a deliberately added test attribute.
- Set a baseUrl in cypress.config.js on day one so every test can use short relative paths with cy.visit, making it trivial to point the whole suite at a staging environment later.
- Use the Test Runner's time-travel snapshots when a test fails locally before adding any debugging code; most failures are visible just by clicking back through the command log.
Common pitfalls
- Adding fixed waits like cy.wait(5000) to work around flaky tests. This hides the real problem and slows the suite down; instead rely on Cypress's automatic retrying by asserting on the state you actually need, such as cy.get('.result').should('be.visible').
- Writing tests that depend on the end state left by a previous test (for example, assuming a user is already logged in because a prior test logged in). Each test should set up its own starting state so it can run alone or in any order.
Selectors, Commands and Assertions
Every Cypress test is built from three ingredients: finding elements, acting on them, and asserting that the application behaves as expected. Getting comfortable with these basics is the foundation for writing reliable end-to-end tests.
Cypress queries the DOM with commands like cy.get(), cy.contains(), and cy.find(). These commands are asynchronous and retry-enabled: Cypress does not immediately fail if an element isn't found, it retries for a default timeout (4 seconds) until the element appears or the timeout expires. This retry-ability is one of Cypress's biggest advantages over older frameworks that require manual waits.
Once an element is located, action commands such as .click(), .type(), and .check() simulate real user interaction. Cypress automatically waits for the element to be actionable (visible, not covered, not disabled) before performing the action.
Finally, assertions verify the state of the page. Cypress supports both implicit assertions (.should(), .and()) chained directly onto commands, and explicit assertions using expect() or assert() syntax borrowed from Chai. Implicit assertions are retried automatically, which makes them the preferred style for most UI checks.
Querying and Chaining Commands
cy.get() is the workhorse selector command, accepting CSS selectors just like document.querySelector. cy.contains() finds elements by their visible text content, which is often more resilient to markup changes than a CSS selector. cy.find() narrows a search to descendants of a previously yielded element, enabling precise, readable chains such as cy.get('.todo-list').find('li').first().
Chaining matters because each command yields a subject that the next command in the chain operates on. Understanding what subject is yielded at each step prevents confusing errors. For example, cy.get('form').find('input').should('have.length', 3) first yields the form, then all inputs inside it, then asserts on that collection.
A key habit to build early is preferring stable, semantic selectors over brittle ones. Selecting by class names tied to styling is fragile because a CSS refactor can silently break tests. Many teams add a dedicated data-cy or data-testid attribute purely for testing purposes, decoupling test selectors from both styling and content changes. This single convention prevents a large share of selector-related test flakiness over a project's lifetime.
Implicit vs Explicit Assertions
Implicit assertions, written with .should() or .and(), are chained directly onto a command and are automatically retried until they pass or the command times out. This makes them ideal for asserting on UI state that may take a moment to settle, such as text appearing after an API call resolves.
Explicit assertions use Chai's expect() syntax, typically inside a .then() callback after the subject has already been yielded. These are not retried, so they are better suited to one-off checks on values you've already captured, such as asserting on a variable derived from multiple prior steps, rather than on live DOM state.
A common pattern is to combine both: use .should() to wait for a condition, then .then() to perform more complex assertions on the resolved value. Cypress also supports negative assertions like .should('not.exist') and chained assertions like .should('have.class', 'active').and('be.visible'), which read naturally and keep test intent clear. Favoring implicit assertions wherever possible is the single most effective way to reduce flaky, timing-related test failures.
describe('Todo list', () => {
it('adds a new todo item', () => {
cy.visit('/todos');
cy.get('[data-cy=new-todo]').type('Buy milk{enter}');
cy.get('[data-cy=todo-item]')
.should('have.length', 1)
.first()
.should('contain.text', 'Buy milk');
cy.get('[data-cy=todo-item]').first().find('input[type=checkbox]').check();
cy.get('[data-cy=todo-item]').first().should('have.class', 'completed');
});
});
A complete test using data-cy selectors, action commands (type, check) and chained implicit assertions to verify an item is added and can be marked complete.
Tips
- Add a dedicated data-cy or data-testid attribute to interactive elements so tests don't break when styling or markup changes.
- Prefer chained implicit assertions (.should, .and) over explicit expect() calls for anything checking live DOM state, since they retry automatically.
- Use cy.contains() for text-driven lookups when there is no stable attribute to select by, but combine it with a scoped parent selector to avoid matching unrelated elements.
Common pitfalls
- Asserting inside a .then() callback on DOM elements instead of using .should(): explicit assertions are not retried, so a slow-to-render element can cause a false failure. Use .should() directly on the command chain instead.
- Selecting elements by CSS classes used for styling: a design change can silently break the test even though the feature works. Use dedicated test attributes that are never touched by CSS or content updates.
Handling Asynchronous Behavior, Network Requests and Fixtures
Cypress code reads like synchronous JavaScript, but under the hood every cy.* call is queued and run later. Understanding this queue is the key to writing reliable tests instead of flaky ones. In this section you'll learn how Cypress manages timing internally, how to control network requests with cy.intercept, how to load reusable test data from fixture files, and how to wait deterministically for specific requests instead of relying on arbitrary pauses.
By the end of this section you should be comfortable replacing brittle cy.wait(1000) calls with cy.wait('@alias'), stubbing an API response entirely so your UI tests don't depend on a real backend, and organizing mock data in fixture files that keep your spec files clean and readable.
The Command Queue: Why Cypress Only Looks Synchronous
Every Cypress command, cy.visit(), cy.get(), cy.click(), returns immediately without doing any work itself. Instead it gets enqueued, and Cypress runs the queue afterward, one command at a time, waiting for each to resolve (and automatically retrying assertions) before moving to the next. This is why you cannot store the result of cy.get('.list-item') in a plain variable and expect it to contain data right away; the command hasn't executed yet at that point in your script.
Instead, Cypress gives you .then() to work with a command's eventual result, much like a promise callback, though Cypress commands are not actual Promises and cannot be awaited with async/await in the usual way. If you need a value outside of the chain, use an alias with .as() and retrieve it later with cy.get('@alias'), or use a closure variable that you assign inside .then() and read in a later command.
Understanding the queue also explains Cypress's built-in retry-ability: commands like cy.get() and assertions automatically retry until they pass or a timeout is reached, which is why you rarely need manual waits for elements to appear. The mental model to keep is: write commands in the order they should run, use .then() to react to a result, and trust the queue rather than trying to mix in native async/await patterns.
Stubbing, Spying and Waiting with cy.intercept
cy.intercept() lets you observe or control any network request your app makes. Used as a spy, it simply records that a request happened so you can assert on its method, URL or body. Used as a stub, it intercepts the request and returns a fixed response you supply, so your test doesn't depend on a real server being up, slow, or returning unpredictable data.
Always set up cy.intercept() before the action that triggers the request (usually before cy.visit() or before a click), because Cypress can only intercept requests made after the intercept is registered. Give the intercept an alias with .as('getUsers') so you can later call cy.wait('@getUsers'), which pauses the test until that specific request completes rather than guessing how long the network might take.
You can also assert on the intercepted request and response together by chaining off cy.wait('@getUsers'), which yields an interception object containing request and response. This lets you verify the exact payload sent by your app, not just the UI outcome, bridging UI testing with lightweight API verification. Combining cy.intercept with fixtures (covered in the code example) keeps your stubbed data in one place instead of scattered inline objects across specs.
// cypress/fixtures/users.json
// [{ "id": 1, "name": "Ada Lovelace" }, { "id": 2, "name": "Alan Turing" }]
describe('User list', () => {
it('loads users from a stubbed API', () => {
cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers');
cy.visit('/users');
cy.wait('@getUsers').its('response.statusCode').should('eq', 200);
cy.get('[data-testid="user-row"]').should('have.length', 2);
cy.contains('Ada Lovelace').should('be.visible');
});
});
Loads mock data from a fixture file, stubs the GET request with it, visits the page, waits for that specific request to resolve, and then asserts on both the response and the rendered UI.
Tips
- Alias every intercept you care about and wait on the alias instead of using fixed-time waits like cy.wait(2000); this makes tests faster and far less flaky.
- Keep fixture files small and focused, one file per shape of data, so specs stay readable and data changes don't ripple across unrelated tests.
- Use cy.intercept as a spy (no stubbed response) when you only want to confirm a request was made correctly, and reserve stubbing for cases where you want to control or remove a backend dependency.
Common pitfalls
- Registering cy.intercept after cy.visit() or after the triggering action: the request has already gone out and Cypress cannot retroactively intercept it, so always set up intercepts first.
- Trying to read a Cypress command's result with a plain variable assignment instead of .then() or an alias: because commands are queued, the variable will be undefined when you try to use it outside the chain.
Organizing a Test Suite with Custom Commands and Page Objects
As a Cypress suite grows past a handful of specs, duplicated selectors and repeated login steps become a maintenance burden. The fix is to pull repeated behavior into custom commands and to group selectors and actions for a given screen into a page object. This keeps each spec file short and readable, and it means a UI change only requires an edit in one place rather than in every test that touches that screen.
Custom commands live in cypress/support/commands.js and are registered with Cypress.Commands.add(). They are ideal for actions that happen in almost every test, such as logging in, seeding a specific app state through the UI, or asserting a toast message appeared. Page objects, by contrast, are plain JavaScript classes or modules that wrap the selectors and interactions for one page or component, so a spec reads like a sequence of business actions (loginPage.submit()) instead of a sequence of raw DOM queries.
A beforeEach hook is the natural place to call a shared setup command, such as logging in or visiting a base URL, so every test in a file starts from a known state without repeating that logic line by line. Fixtures, kept under cypress/fixtures, should hold the static data a test needs (a user record, a product list) and should be loaded with cy.fixture() rather than hard-coded inline, which keeps data changes separate from test logic.
As the suite scales, keep selectors centralized: a single page object owning its selectors avoids the situation where ten specs each contain a slightly different copy of the same CSS string.
Writing Reusable Custom Commands
A custom command is the right tool when the same sequence of Cypress calls appears in many specs. Define it once in cypress/support/commands.js and it becomes available as cy.yourCommand() everywhere, because that file is loaded by cypress/support/e2e.js before any spec runs.
Good candidates for custom commands include authentication, API-based setup that bypasses the UI for speed, and common assertions like checking that an element's text matches an expected value. Keep commands focused: a command that does one thing well (cy.login(email, password)) is easier to reuse and debug than one that tries to handle every possible login variant with flags and options.
Commands can also wrap existing commands to add retry-friendly assertions, and they can return a chainable so later commands in the same chain still work as expected. Overwriting a built-in command with Cypress.Commands.overwrite() is possible but should be used sparingly, since it changes behavior for the entire suite and can confuse anyone reading a spec that assumes default behavior.
Document custom commands with a short comment above each definition describing what it does and what it expects as arguments. In a large suite, this acts as living documentation that saves new contributors from having to read the implementation just to use the command correctly. Keep the file itself organized by grouping related commands together, for example all authentication commands at the top, followed by data-seeding commands, followed by assertion helpers.
Structuring Page Objects and Shared Setup
A page object is a plain module that exposes methods for the actions available on one screen, and getters for the elements on it. It does not contain assertions itself in most styles; instead, the spec file calls the page object's methods and then makes its own assertions, which keeps the separation between 'how to interact with the page' and 'what the test expects to be true' clean.
Organize page objects under a folder such as cypress/support/pages, one file per screen or major component, and import only what a given spec needs. This avoids a single enormous file holding selectors for the entire application, which becomes hard to navigate and merge in a team setting.
Shared setup belongs in beforeEach, not repeated in every it block. A typical pattern visits a base page and logs in through a custom command, so each test starts from the same known state. Keep beforeEach lean. If only one or two tests in a file need extra setup, do that inside those specific tests rather than adding conditional logic to the shared hook.
As the suite grows, review page objects periodically to remove methods that are no longer called by any spec, since dead helper code accumulates quietly and makes the codebase harder to trust.
// cypress/support/commands.js
Cypress.Commands.add('login', (email, password) => {
cy.session([email, password], () => {
cy.visit('/login');
cy.get('[data-testid="email"]').type(email);
cy.get('[data-testid="password"]').type(password);
cy.get('[data-testid="submit"]').click();
cy.url().should('include', '/dashboard');
});
});
A reusable login command that uses cy.session to cache the authenticated state across tests, avoiding repeated UI logins and speeding up the suite.
// cypress/support/pages/loginPage.js
class LoginPage {
visit() {
cy.visit('/login');
}
fillEmail(email) {
cy.get('[data-testid="email"]').type(email);
}
fillPassword(password) {
cy.get('[data-testid="password"]').type(password);
}
submit() {
cy.get('[data-testid="submit"]').click();
}
}
export default new LoginPage();
// cypress/e2e/login.cy.js
import loginPage from '../support/pages/loginPage';
describe('Login', () => {
beforeEach(() => {
loginPage.visit();
});
it('logs in with valid credentials', () => {
loginPage.fillEmail('user@example.com');
loginPage.fillPassword('correct-password');
loginPage.submit();
cy.url().should('include', '/dashboard');
});
});
A minimal page object for a login screen, keeping selectors and actions in one file while the spec focuses on the test flow and its assertions.
Tips
- Use data-testid attributes for selectors inside page objects and custom commands so UI styling or markup changes do not break the suite.
- Prefer cy.session for login flows so repeated authentication does not slow down every test file.
- Keep custom commands single-purpose; a command that does one clear thing is easier to reuse and to debug when it fails.
Common pitfalls
- Putting assertions inside page object methods, which hides what a test is actually checking; keep assertions in the spec file so intent stays visible.
- Letting one giant page object file grow to cover the whole app, making it hard to find or safely edit a single selector; split page objects by screen or component instead.
Running Cypress in Continuous Integration
Running Cypress locally proves your tests work on your machine, but the real payoff comes from running them automatically on every push and pull request. Continuous integration (CI) catches regressions before they reach production and gives a team a shared, objective signal about whether a change is safe to merge.
Cypress ships with everything needed for CI out of the box: cypress run executes your spec files headlessly (no visible browser window), prints results to the terminal, and exits with a non-zero code if any test fails, which is exactly what a CI pipeline needs to decide whether to pass or fail a build.
This section covers three practical concerns: choosing and configuring a browser for headless execution, splitting a large suite across multiple parallel jobs so a full run does not block your pipeline for too long, and capturing artifacts (screenshots and videos) so a failure can be diagnosed without re-running the suite locally. We then wire all of this into a real pipeline definition.
A few ground rules apply across every CI provider. Install dependencies with a locked, reproducible command (npm ci, not npm install), cache the node_modules and Cypress binary cache between runs to avoid re-downloading the browser binary on every job, and make sure your application is actually running and reachable before Cypress starts (either by starting a server in a previous step or using a tool like start-server-and-test). Treat your CI config as part of the test suite: if it silently swallows a failure or never actually executes the tests, it is worse than having no CI at all.
Headless Browsers, Parallelization, and Artifacts
By default cypress run launches Electron, Cypress's bundled browser, headlessly. You can target a different installed browser with the --browser flag, for example cypress run --browser chrome or cypress run --browser firefox, which is useful when you need to reproduce a bug that only shows up in a specific engine. Most CI images (GitHub Actions' ubuntu-latest, for instance) already include Chrome and Firefox, but you should pin a known-good version where possible, since browser updates can occasionally shift behavior mid-pipeline.
As a suite grows past a few dozen specs, a single CI job running everything sequentially becomes the bottleneck in your pipeline. Cypress supports splitting a suite across several parallel machines with the --parallel and --record flags, which requires a Cypress Cloud project and record key; each machine pulls the next unrun spec file from a shared queue rather than following a hardcoded split, so the work balances automatically even if some specs are slower than others.
For diagnosing failures without re-running locally, Cypress captures a screenshot automatically on every failed test and, if video: true is set in your config, records a video of the whole spec run. In CI you typically want to upload these as build artifacts (most providers have a dedicated 'upload artifact' step) so a teammate can open the failure screenshot or video directly from the failed pipeline run instead of asking you to reproduce it.
Wiring Cypress into a Pipeline
A typical CI job for Cypress does four things in order: check out the code, install dependencies, start the application under test, and run the suite. The exact syntax differs by provider, but the shape is consistent across GitHub Actions, GitLab CI, Jenkins and CircleCI.
A common pitfall is running Cypress before the application is actually ready to accept requests, which produces flaky 'connection refused' failures that have nothing to do with your tests. The start-server-and-test npm package solves this cleanly: it starts your dev or preview server, polls a URL until it responds, then runs the given test command and shuts the server down afterward.
When you run the suite on every pull request, make sure the job is required to pass before a merge is allowed (most Git hosting platforms let you mark a CI check as required in branch protection settings). Otherwise a red Cypress run becomes a suggestion rather than a gate, and regressions slip through anyway. It is also worth running the full suite on the main branch after merge, in addition to pull requests, to catch issues introduced by merging two individually-passing branches together.
name: Cypress Tests
on: [pull_request]
jobs:
cypress-run:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install dependencies
run: npm ci
- name: Build and start app, then run Cypress
run: npx start-server-and-test 'npm run start' http://localhost:3000 'npx cypress run --browser chrome'
- name: Upload screenshots on failure
if: failure()
uses: actions/upload-artifact@v4
with:
name: cypress-screenshots
path: cypress/screenshots
- name: Upload videos
if: always()
uses: actions/upload-artifact@v4
with:
name: cypress-videos
path: cypress/videos
A GitHub Actions workflow that installs dependencies, starts the app and waits for it to be reachable, runs the Cypress suite headlessly in Chrome, and uploads screenshots and videos as build artifacts so a failed run can be inspected from the Actions tab.
# Splitting a suite across 4 parallel machines (requires Cypress Cloud)
jobs:
cypress-run:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
containers: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npx cypress run --record --parallel --key ${{ secrets.CYPRESS_RECORD_KEY }}
Uses a GitHub Actions matrix to launch four identical jobs that each connect to Cypress Cloud with the same run; Cypress automatically divides the spec files between them so the suite finishes roughly four times faster than a single sequential run.
Tips
- Cache the Cypress binary (usually under ~/.cache/Cypress) and node_modules between CI runs to avoid a multi-minute download on every job.
- Pin browser versions in your CI image where you can, since an unexpected browser update can introduce flakiness that has nothing to do with your application code.
- Always upload screenshots and videos as build artifacts on failure; it turns a 'works on my machine' debugging session into a two-click download from the failed pipeline run.
Common pitfalls
- Running `cypress run` before the application server is actually ready, causing connection-refused errors unrelated to the tests; fix this by using a tool like start-server-and-test to wait for a health check before launching Cypress.
- Marking the Cypress job as optional in branch protection rules, which lets pull requests merge even when the suite is red; make the CI check required so failures actually block a merge.
Exercises
Exercise 1: Set Up a Cypress Project and Write a First Test
In this exercise you will create a new Node.js project, install Cypress, configure it to point at a public demo page, and write a single end-to-end test that verifies a page loads correctly. This exercise reinforces the installation steps and folder structure covered in the first section, and gets you comfortable opening and reading the interactive Test Runner before moving on to more complex selectors and assertions in later sections. Take your time reading the command log in the Test Runner after the test passes; understanding what each line represents will make debugging failures much faster later in the course.
- Create a new folder and run npm init -y, then install Cypress as a dev dependency with npm install cypress --save-dev.
- Run npx cypress open and let Cypress scaffold the default folder structure, choosing the e2e testing type when prompted.
- Edit cypress.config.js to set baseUrl to a public demo site of your choice that you are allowed to test against.
- Create a new file in cypress/e2e named homepage.cy.js and write a test that visits the base URL and asserts that a known piece of text is visible on the page.
- Run the test from the interactive Test Runner and confirm it passes, then run it headlessly from the terminal with npx cypress run.
Expected outcome: A working Cypress project where a single test visits the configured base URL and passes both in the interactive Test Runner and when run headlessly from the command line.
Exercise 2: Replace Fragile Selectors and Remove Fixed Waits
You will be given a short Cypress test file that uses CSS class selectors and a hard-coded cy.wait(3000) to work around a loading spinner. Your task is to rewrite the test so it uses data-testid attributes for every selector and waits on the actual disappearance of the spinner element instead of a fixed delay, relying on Cypress's built-in retry-ability. This exercise is meant to build the habit of asserting on real page state rather than guessing at timing, which is one of the most common sources of flaky automated test suites.
- Start from a test file that selects elements using .btn-submit and .user-name class selectors and includes cy.wait(3000) after clicking submit.
- Add data-testid attributes to the relevant elements in the sample application's HTML, or note where you would add them if you cannot edit the markup.
- Rewrite every selector in the test to use cy.get('[data-testid=...]') instead of the class-based selector.
- Remove the cy.wait(3000) call and replace it with an assertion such as cy.get('[data-testid="spinner"]').should('not.exist') before continuing the test.
- Run the test several times in a row to confirm it passes consistently without the fixed wait.
Expected outcome: A rewritten test file that uses only data-testid selectors, contains no fixed-duration waits, and passes reliably across repeated runs.
Quiz
1. Why does Cypress generally need fewer explicit waits in its tests compared to a tool that drives the browser from an external process?
- Cypress test files are compiled before running, removing timing issues
- Cypress commands run in the same run loop as the application and automatically retry queries and assertions until a timeout is reached
- Cypress disables all JavaScript timers on the page under test
- Cypress always runs tests in a headless browser, which is inherently faster
Show answer
B. Cypress commands run in the same run loop as the application and automatically retry queries and assertions until a timeout is reached
Because Cypress executes inside the same browser context as the application, its commands and chained assertions can retry automatically for a configurable timeout instead of failing immediately, which removes most of the need for manual waits.
2. Where does Cypress expect end-to-end test files to live by default?
- In a folder named tests at the project root
- In cypress/e2e
- In node_modules/cypress/tests
- Anywhere, as long as the file ends in .test.js
Show answer
B. In cypress/e2e
A standard Cypress project scaffolds a cypress/e2e folder, and Cypress automatically discovers test files placed there without any separate registration step.
3. What is the main problem with writing cy.wait(5000) to wait for a loading spinner to disappear?
- cy.wait does not accept a number as an argument
- It is not valid Cypress syntax and will throw an error
- It wastes time when the spinner disappears sooner and can still fail if the spinner takes longer than five seconds
- It only works in the interactive Test Runner, not in headless mode
Show answer
C. It wastes time when the spinner disappears sooner and can still fail if the spinner takes longer than five seconds
A fixed wait is both wasteful, since the test always pauses for the full duration even if the condition is met sooner, and fragile, since it will fail if the real wait time ever exceeds the fixed value; asserting on the actual state, like the spinner's non-existence, is more reliable.
4. What is the purpose of setting a baseUrl in cypress.config.js?
- It sets the URL where the Cypress Test Runner itself is hosted
- It lets tests use short relative paths with cy.visit instead of a full URL every time
- It is required for Cypress to install correctly
- It determines which browser Cypress launches by default
Show answer
B. It lets tests use short relative paths with cy.visit instead of a full URL every time
Configuring baseUrl means a test can call cy.visit('/login') instead of the full address, which also makes it easy to point the whole suite at a different environment by changing one configuration value.
5. Why is it recommended to prefer data-testid attributes over CSS classes when selecting elements in a Cypress test?
- data-testid attributes make the page load faster
- Cypress cannot select elements by class name
- CSS classes and visible text tend to change more often for styling or content reasons, while a dedicated test attribute is added specifically to stay stable for tests
- data-testid is required by the HTML specification for form elements
Show answer
C. CSS classes and visible text tend to change more often for styling or content reasons, while a dedicated test attribute is added specifically to stay stable for tests
Class names often change when styling is refactored and visible text changes with copy edits or translations, whereas a data-testid attribute exists purely to give tests a stable hook, making tests less likely to break for reasons unrelated to actual functional changes.