Cypress in GitHub Actions runs through the official cypress-io/github-action, which takes care of the whole run scaffold. It installs dependencies, caches the binary, starts the app (start), waits for the URL (wait-on) and runs cypress run. Without waiting, the first cy.visit() sometimes fails with a connection error because the background server is not listening yet. Secrets come from secrets, and screenshots are saved with upload-artifact using if: failure().
Cypress · CI
Green locally, but in CI the first test fails with connection refused. What is missing?
Locally a developer already has dependencies, the Cypress binary and a running app. A clean CI machine has none of it: the code, the dependencies, the Cypress binary, the server and the order they start in all have to be described. This lesson shows how the official cypress-io/github-action covers this, what it does step by step and what stays your job: secrets, artifacts, permissions.
How it works and why. The action merges what you would otherwise assemble from five commands: it installs dependencies with the command it picks by lock file (npm ci, yarn --frozen-lockfile or pnpm install --frozen-lockfile), caches the Cypress binary, starts the app in the background (start), waits for the URL (wait-on) and calls cypress run. The Cypress exit code becomes the step result, so the job goes red when tests fail. Recording to Cypress Cloud and parallelisation are switched on by the record and parallel fields of the same action.
What happens on a clean machine
Figure 1. Step 4 is the one most often forgotten: without it tests may start before the server listens on the port.
Example: from "works on my machine" to a stable workflow. A typical first attempt just repeats the local commands:
# Before: server in the background, tests start at once
- run: npm ci
- run: npm start &
- run: npx cypress run
Reading the error: the server is not listening yet
1CypressError: cy.visit() failed trying to load:
http://localhost:3000/
We attempted to make an http request to this URL but the request failed without a response.
We received this error at the network level:
> Error: connect 2ECONNREFUSED 127.0.0.1:3000
Common situations why this would fail:
- you don't have internet access
3- you forgot to run / boot your web server
- your web server isn't accessible
- you have weird network configuration settings on your computer
What:cy.visit itself failed, before the first assertion. The test checked nothing: the page could not be opened.
Why:ECONNREFUSED means nobody listens at that address and port. The app has not started yet or has already crashed.
Hint: the line about a server that was not started is the one that matters in the list. The internet has nothing to do with it.
What to do
Start the server with the start option and wait for it with wait-on instead of npm start &: then the tests begin once the port answers.
Figure 2. The real error text: the numbers lead to the explanations.
The background process only starts. Nothing promises that the server already listens on the port when the next step begins, so the first cy.visit() sometimes fails with a connection error and a re-run passes. That "random" behaviour is the sign of a race. The working version is the official action plus an artifacts step:
What matters here. wait-on blocks the step until the URL answers, so there is no race. Variables with the CYPRESS_ prefix become Cypress environment values (CYPRESS_USER_PASSWORD is read in a test with cy.env(['USER_PASSWORD']); Cypress.env() was removed in Cypress 16). A GitHub secret is masked in logs, but it is available in plain form to the test code, so use a test account with minimal rights. The upload-artifact step has if: failure(): without it the step is skipped after the previous step fails, because success() is the default. The permissions block leaves the token read-only, and timeout-minutes stops a hung run from eating the minutes quota.
Limits and alternatives. The action does not choose a test strategy for you: what runs on a PR and what runs nightly is your decision (spec, tags, separate workflows). Recording to Cypress Cloud is switched on like this:
Secrets are not passed to workflows triggered from forks through pull_request, so the record key is empty there and a job with record: true on a fork PR fails. For external contributors make a separate job without recording. If you need specific browser or OS versions, use a container instead of the runner's built-in Chrome (see the lesson on Docker images). The same scenario in Playwright needs no dedicated action:
The difference is not about a "better" tool: Playwright installs its own browsers with the install command, while Cypress takes its binary from the cache, so the whole "frame" lives in the action itself.
Typical mistakes.
npm start & npx cypress run with no waiting: the first tests fail with a connection error and a re-run "heals" it. The cause is a race, not the tests.
An artifacts step without if: failure() or !cancelled(): it does not run after the tests fail, so there are no screenshots exactly when you need them.
Old major versions of actions copied from old examples. Take the current ones (checkout, upload-artifact and cypress-io/github-action at v7) and read the action README.
Passwords in cypress.config.ts or in the repository instead of secrets.
Check yourself
The workflow starts the server as npm start & and then npx cypress run. The first test fails, a re-run is green. What is it and how do you fix it?
Answer
It is a race: the background process has started but the port is not yet listening when Cypress makes its first request. Fix: start with wait-on in cypress-io/github-action, or start-server-and-test, so tests begin only after the URL answers.
An upload-artifact step stands after the tests with no condition. The tests failed and there are no screenshots in the artifacts. Why?
Answer
By default a step has the condition success() and is skipped when the previous step failed. Add if: failure() (only on failure) or if: ${{ !cancelled() }} (always, except cancellation).
Related lessons: “How to start the app before Cypress tests in CI?”, “How to install and cache Cypress in CI?”, “Which Cypress Docker images to use in CI?”.
In the interview.Junior: I use the official cypress-io/github-action: it installs dependencies with a cache, starts the app, waits for it and runs the tests. I pass secrets from the repository secrets and save screenshots as artifacts on failure. Tests run on every pull request. Middle/Senior: I look at the reliability of the frame: wait-on instead of a race, minimal permissions, timeout-minutes, artifacts with the right condition, a pinned image or browser versions. I switch on Cloud recording separately, and it is unavailable for fork PRs because there are no secrets. What runs on a PR and what runs nightly I decide by feedback time.
How do you parallelise Cypress tests?
One cypress run drives one browser and runs specs one after another, so parallelism in Cypress means several machines, not several processes on one. The unit of distribution is a spec file. The official way is Cypress Cloud with --record and --parallel, which balances specs dynamically. A free alternative is a CI job matrix with the cypress-split plugin. Parallel jobs need isolated data.
Cypress · Parallelism
A run takes 40 minutes. Can you just start Cypress in several processes on one machine?
Two hundred specs at ten to twelve seconds each add up to about forty minutes of sequential running, and PR feedback becomes too slow. In Playwright the answer "add workers" works on one machine. In Cypress it does not: one process drives one browser and runs specs one after another. This lesson explains why and shows two ways to split the work between machines.
How it works and why. Cypress runs the test in the browser, so one cypress run serves one browser and one spec at a time. Parallelism means several independent runs on different machines (or containers), each with its own browser. The unit of distribution is a spec file: inside a file tests run sequentially. So speed depends on two things: how many machines and how even the shares turn out. The two approaches differ in who decides which spec goes to which machine.
Who distributes the specs
Cypress Cloud
Dynamic distribution
Each machine asks the service for the next spec, and the service uses duration history. Uneven specs even out by themselves. Recording and a key are needed; beyond the free limit it is paid.
cypress-split
Static distribution
Each job computes its share of specs in advance from SPLIT and SPLIT_INDEX. No service or key, but one heavy spec keeps its job longer than the rest.
Figure 1. Both approaches are legitimate: they are different trade-offs between convenience and cost, not "bad" and "good".
Example: 40 minutes on 4 machines. The free route: a matrix of four jobs and the cypress-split plugin. The plugin is wired in the config:
// cypress.config.tsimport { defineConfig } from'cypress';
import cypressSplit from'cypress-split';
exportdefaultdefineConfig({
e2e: {
setupNodeEvents(on, config) {
cypressSplit(on, config); // leaves this job only its share of specsreturn config;
},
},
});
And the matrix gives each job the total and its own index:
strategy.job-index starts at zero, and so does SPLIT_INDEX, so the matrix values fit without conversion. fail-fast: false stops the first red job from cancelling the rest: otherwise you would not see part of the results. The artifact name contains the index because, since upload-artifact v4, several jobs cannot write to one artifact with the same name. The expected gain is roughly a quarter of the test time plus each job's overhead (checkout, cache, server start), so four machines do not give exactly ×4.
The official route through Cypress Cloud looks like this:
All machines with the same group and build id (ci-build-id) count as one run. For most CI providers (GitLab and Jenkins among them) Cypress detects the id automatically; the --ci-build-id flag is needed only when detection fails. Cypress rejects the --parallel flag without --record: the balancing is done by the service, so without recording nobody distributes the specs.
Limits and alternatives. The free Cypress Cloud plan includes parallelisation and load balancing within a monthly limit of test results (500 at the time of writing), and beyond it is paid: check the current terms on the pricing page. Static splitting is cheap but sensitive to skew: one 15-minute spec among small ones keeps its job longest, and extra machines no longer help. Parallel jobs also share the environment: if they write to a shared database or one account, tests start to interfere, so data must be isolated. In Playwright the same work is done by workers on one machine (half the cores by default) and --shard=1/4 across machines with merge-reports for merging the reports, and the default unit is also a file, with fullyParallel: true a single test.
Typical mistakes.
Expecting parallelism on one machine: Cypress runs specs sequentially, several machines are needed.
Keeping a few huge specs: they become the bottleneck. Split them by scenario.
Shared data between parallel jobs (one user, one database): tests break each other and flakiness appears.
Forgetting fail-fast: false or unique artifact names: part of the diagnostics disappears.
Check yourself
A matrix of four jobs with cypress-split, but one spec takes 15 minutes and the rest a second each. Why did the run barely speed up and what do you do?
Answer
A spec is indivisible: one job runs it, and the whole run lasts at least as long. Split the big spec into several files by scenario, then they can be spread across machines.
Why does cypress run --parallel without --record not work?
Answer
Distribution of specs between machines is done by Cypress Cloud while the run is recorded. Without recording there is no service, so Cypress rejects the flag.
Related lessons: “How do you run Cypress in GitHub Actions?”, “Flaky tests in Cypress and retries”, “A test is flaky on CI. How do you look for the cause in Cypress?”.
In the interview.Junior: On one machine Cypress runs specs sequentially, so parallelisation is possible only across several machines. The official way is Cypress Cloud with record and parallel, but beyond the free limit it is paid. For free you can build a matrix in CI and split the specs with the cypress-split plugin. Middle/Senior: The unit of distribution is a spec file, so I keep specs small and similar in duration. Cloud balances dynamically from history, while static splitting is sensitive to skew. Parallel jobs need isolated data, distinct artifact names and fail-fast: false, and the reports have to be merged.
What reports, screenshots and videos does Cypress give you?
In cypress run mode Cypress takes a screenshot on failure by itself, while video has been off by default since version 13. Video is switched on with video: true. Reports go through Mocha reporters: spec in the console, junit or json to files, and mochawesome or Allure as third-party ones. Everything lies on the runner's disk, so artifacts are saved by a step with a failure condition.
Cypress · Reports and artifacts
A test failed in CI. What to open first: the console, a screenshot, a video or a report?
A test failed in the pipeline but passes locally. The machine is already gone, so the only thing left of the run is what you managed to save. This lesson is about what Cypress creates by itself, what has to be switched on, which reports exist and how to bring them from CI to a person.
How it works and why. In cypress run mode Cypress takes a screenshot on failure by itself (screenshotOnRunFailure is true by default), while video has been off by default since Cypress 13 and is switched on with video: true. The files lie in cypress/screenshots and cypress/videos. Reports go through Mocha reporters: the built-in spec works in the console, while junit or json write files. Third-party reporters (mochawesome, Allure) are connected through the same reporter field or through a plugin in setupNodeEvents. All of this lies on the runner disk, so without a step that keeps artifacts it vanishes with the machine.
The path of an artifact from CI to a person
Figure 1. The weakest link: files on the runner disk. They must be kept before the job ends.
Which question each one answers (the table helps to choose what to enable):
What
What question it answers
What it costs
Screenshot on failure
What the page looked like at the moment of failure
Little space, on by itself
Video
What happened before the failure, animations, order of actions
More space and time, must be turned on
JUnit XML
What failed, for the tests tab in CI
Cheap, but with no picture of the page
Mochawesome / Allure
An HTML report, history and trends (Allure)
Extra packages and report merging
Test Replay (Cloud)
Replay of DOM, network and console after the run
Cloud and a recorded run
Example: a configured run. The config switches video on, writes JUnit with a separate file per spec ([hash] in the path stops specs from overwriting each other) and deletes videos of specs without failures. Such a recipe exists in the Cypress documentation:
// cypress.config.tsimport { defineConfig } from'cypress';
import fs from'node:fs';
exportdefaultdefineConfig({
video: true, // false by default
screenshotOnRunFailure: true, // true by default
reporter: 'junit',
reporterOptions: {
mochaFile: 'results/junit-[hash].xml', // its own file per spec
},
e2e: {
setupNodeEvents(on) {
// delete videos of specs without failures: fewer artifactson('after:spec', (spec, results) => {
const failed = results?.tests?.some((test) =>
test.attempts.some((a) => a.state === 'failed'),
);
if (results?.video && !failed) fs.unlinkSync(results.video);
});
},
},
});
Then a CI step keeps everything needed even when the tests failed:
For an HTML report mochawesome usually writes one JSON per spec, and they have to be merged:
# mochawesome: first JSON from every spec, then merge and HTML
npx mochawesome-merge "cypress/reports/*.json" > merged.json
npx marge merged.json --reportDir report
Limits and alternatives. Video does not show the network and the DOM in detail; for that there is Test Replay in Cypress Cloud. Allure adds history and trends through the allure-cypress package, but it needs the results kept between runs. None of this replaces reading the error text: it is often enough, and the screenshot only confirms a guess. In Playwright the same is built in and stronger: an HTML report with Trace Viewer and settings in use:
Expecting video out of the box: since Cypress 13 it must be switched on, while the screenshot on failure is taken by itself.
Keeping artifacts with no condition or only on success(): they are missing exactly on failure.
One report file for all specs: the next spec overwrites the previous one. Use [hash] or merging.
Keeping the video of every spec with no retention period: artifacts quickly fill the quota.
Check yourself
A test failed in CI and the artifacts have a screenshot but no video, although nobody turned video off in the config. Why?
Answer
Since Cypress 13 video is off by default and must be enabled with video: true, whereas cypress run takes the failure screenshot by itself.
All specs write JUnit to one file, and the CI tab shows only the last one. What do you change?
Answer
Each spec overwrites the file. Add [hash] to mochaFile (for example results/junit-[hash].xml) so each spec writes its own file.
Related lessons: “Flaky tests in Cypress and retries”, “How do you run Cypress in GitHub Actions?”, “What Node events does Cypress have, for example after:run?”.
In the interview.Junior: On failure in run mode a screenshot is taken automatically, and video has to be switched on explicitly because it has been off since version thirteen. For HTML reports I use mochawesome, for history and trends Allure through allure-cypress, for CI systems JUnit XML. Middle/Senior: I keep artifacts with the !cancelled() condition and a retention period, and delete videos of specs without failures. For parallel jobs I merge the reports and give each spec its own JUnit file. For deep diagnostics I use Test Replay in Cloud.
Flaky tests in Cypress and retries
Retries rerun a test from the start after a failure, but only mask instability. A test that passed on a retry is a signal, not a fix. Typical causes are a fixed cy.wait, a race with the network, dependencies between tests and an unstable selector. They are removed by waiting for a condition: a request alias with a specific enough URL and retrying assertions.
Cypress · Flaky
A test is green only on the third attempt. Was it cured or hidden?
Turning on retries is easy and CI turns green at once. It is harder to notice that the unstable test has not gone anywhere: it just costs extra seconds and trust on every run. The lesson separates two things: how to find and remove the root cause and how to keep retries under control.
How it works and why. Cypress retries commands and assertions inside a test, but if the test still fails, a retry starts it again from the beginning: the beforeEach and afterEach hooks run again, while before and after do not. By default both runMode and openMode are 0, which means no retries. The report shows the attempts: a test that passed on a retry is marked as flaky. This is information, not a verdict: it tells you the test is unstable.
Two roles of retries
Wrong
Retries as a cure
Set retries: 5 everywhere, CI is green, the cause remains. Flaky tests grow and the run slows down.
Right
Retries as a safety net
Few attempts (1-2) only in run mode, and every test that passed on a retry is recorded and investigated.
Figure 1. Retries cure nothing by themselves: they only buy time for investigation if a pass on a retry is not lost.
Example: from a pause to waiting for a condition. The most frequent root cause is a fixed pause that guesses when the data arrives:
// Flaky: a fixed pause and a race with the server response
cy.visit('/orders');
cy.get('[data-cy=filter]').type('paid');
cy.wait(2000);
cy.get('[data-cy=row]').should('have.length', 3);
Two seconds is enough on a fast machine and not enough on slow CI, so the test fails "every other run". The cure is to wait for exactly the request that supplies the data.
// Stable: wait for exactly the right request
cy.intercept('GET', '/api/orders?status=paid').as('paid');
cy.visit('/orders');
cy.get('[data-cy=filter]').type('paid');
cy.wait('@paid');
cy.get('[data-cy=row]').should('have.length', 3);
One detail matters here: the alias fires on the first matching request. If the intercept were for a general /api/orders*, cy.wait would catch the request from cy.visit, not the one from the filter, and the test would stay unstable. So the URL must be specific enough. Flaky causes go well beyond pauses:
Cause
How it shows up
Cure
Fixed cy.wait
Passes on a fast machine, fails on a slow one
Wait for a condition: a request alias or an assertion
Race with the network
Data has not arrived when the test asserts
cy.intercept + cy.wait('@alias')
Dependency between tests
Fails only in another order or in parallel
Each test prepares its own state through the API
Unstable selector
Sometimes finds the wrong element
data-cy instead of classes and text
Slow CI
Timeouts only on CI
Check resources instead of raising timeouts at random
Retries are set in the config, and can be overridden for a single test or a describe block:
// cypress.config.tsexportdefaultdefineConfig({
retries: { runMode: 2, openMode: 0 }, // 0 and 0 by default
});
// a single test or a blockdescribe('Orders', { retries: 1 }, () => {
it('filters by status', { retries: { runMode: 3 } }, () => {});
});
Limits and alternatives.openMode: 0 is kept deliberately: during development a failure must be visible at once. Retries hide not only flaky tests but real rare bugs too (a race in the product), so a test that passes on a retry deserves to be treated as a signal. For diagnosis, screenshots of each attempt, video and Test Replay in Cypress Cloud help, and Cloud shows flaky tests separately. Quarantine and re-run strategies at the pipeline level are covered in a separate lesson. Playwright has the same idea (retries in the config and trace: 'on-first-retry'), so the principle does not depend on the tool.
Typical mistakes.
Treating instability by raising retries or timeouts: the run slows down and the cause remains.
Not looking at which tests passed on a retry: a green CI creates false confidence.
Relying on before for state that the test changes: after a retry it is not restored, because before does not repeat.
Tests that depend on each other and on shared data: they fail only in another order or in parallel.
Check yourself
A test always passes on the second attempt. CI is green. Why is that not a reason to relax?
Answer
A pass on a retry means the test is unstable: the cause (race, pause, shared data) remains and the retry hides it. It may also be a real rare bug in the product. The root cause has to be found.
There is one alias for /api/orders* covering cy.visit and the filter, and cy.wait('@orders') stands after the filter. Why does the test still flake?
Answer
The first cy.wait('@orders') catches the request from cy.visit, not from the filter, so the assertion may run before the filter response. Make the intercept URL specific (?status=paid) or wait for the second request.
Related lessons: “Why is cy.wait(3000) an antipattern and what to use instead?”, “How do you wait for a request and check it through an alias?”, “A test is flaky on CI. How do you look for the cause in Cypress?”, “Flaky tests in CI: retries, quarantine, re-runs”.
In the interview.Junior: Flaky tests usually come from fixed pauses, races with the network, test dependencies and unstable selectors. I cure them by waiting for conditions: intercept with an alias and retried assertions. I configure retries in the config: runMode for CI, openMode for interactive mode. Middle/Senior: Retries should be small and only in run mode, and every pass on a retry is recorded and investigated: it is a safety net, not a cure. I look at the screenshots of attempts, video and Test Replay, isolate data through the API and make sure the intercept URL is specific enough.
Cypress in Jenkins or GitLab CI
In GitLab CI and Jenkins, Cypress runs with the same npx cypress run in an official image that ships with browsers; only the syntax changes. The steps are the same: npm ci, cache, start the app and wait for it, run, and save artifacts even after a failure. Secrets come from CI/CD variables or credentials, and a JUnit report shows results in the test tab.
Cypress · CI
The pipeline is in GitLab CI or Jenkins, not GitHub Actions. What changes and what stays?
GitHub Actions has a ready action that takes over most steps. GitLab CI and Jenkins do not, and it seems that everything has to be invented anew. In reality only the syntax changes: the same steps (image, dependencies, server, run, artifacts) are written in different words. The lesson shows what is shared and what is specific, with two working examples.
How it works and why. At the core is npx cypress run with the needed parameters: browser, config, specs, environment variables. The most convenient is an official cypress/included or cypress/browsers image where browsers and system libraries are already installed. Then four things are needed that the action does in Actions: install dependencies (npm ci), cache the npm cache and the Cypress binary, start the app and wait for it (start-server-and-test or wait-on) and, after the run, keep artifacts even on failure. Secrets are passed through CI/CD variables (GitLab) or credentials (Jenkins) and do not lie in the repository.
The same in three systems:
Need
GitHub Actions
GitLab CI
Jenkins
Image with browsers
container.image
image:
Docker agent
Cache
actions/cache
cache:
a plugin or an agent volume
Secrets
secrets.*
CI/CD variables
credentials
Parallelism
strategy.matrix
parallel:
parallel stages
Report in a tab
an artifact
artifacts:reports:junit
the junit step
Example: GitLab CI. This is a separate job in .gitlab-ci.yml. The cache is tied to the lock file, and the cache folders are moved into the working directory because GitLab caches only paths inside the project. parallel: 3 creates three copies of the job, each with its own CI_NODE_INDEX:
artifacts:when: always keeps the files after a failure too, and reports:junit shows results in the tests tab of the merge request. The split of specs between the three copies is done here by the cypress-split plugin, as in the lesson on parallelism.
Example: Jenkins. In Jenkins it is a stage in the Jenkinsfile, and the pipeline runs in a Docker agent:
The post { always } block runs regardless of the stage results: the junit step reads the XML and shows the results in the build (junit alone marks the build unstable, but here the sh step running cypress run has already failed it), and archiveArtifacts keeps screenshots and video. Jenkins masks the secret from credentials() in logs. If npm in the container complains about permissions to the home directory, redirect the cache to the working directory, as in the GitLab example.
Limits and alternatives. Parallelisation here is also done by several jobs: manually or through parallel: in GitLab, or through Cypress Cloud with --record --parallel. Artifacts: Cypress takes screenshots on failure by default, while video is off by default and is switched on with video: true; the cypress/screenshots and cypress/videos folders are kept even on failure (when: always, post { always }) with a limited retention so as not to take up space. For reports, mochawesome or Allure are used, and the JUnit reporter gives data for the tests tab if the system can read JUnit XML. Notifications in Slack or Teams with the result and a link to the report are set up separately.
Typical mistakes.
Running cypress run right after starting the server with no waiting: the first tests fail with a connection error.
Caching with a bad key or no key: old binaries pile up in the cache.
Keeping artifacts only on success: in GitLab this is when: always, in Jenkins the post { always } block.
Logins and tokens in the repository instead of CI/CD variables or credentials.
Check yourself
In a GitLab job with parallel: 3 all three copies run the same specs. What is missing?
Answer
parallel only creates copies of the job and sets CI_NODE_INDEX and CI_NODE_TOTAL. Specs are split between copies by a separate mechanism: cypress-split (pass SPLIT and SPLIT_INDEX) or Cypress Cloud with --parallel.
The tests failed, the Jenkins build is red and there are no screenshots in the archive. Where do you look?
Answer
Probably archiveArtifacts stands in a stage after the run that failed, so it did not execute. Put it in post { always } and check that the path matches the screenshots folder.
Related lessons: “How do you run Cypress in GitHub Actions?”, “How do you parallelise Cypress tests?”, “What reports, screenshots and videos does Cypress give you?”, “Which Cypress Docker images to use in CI?”.
In the interview.Junior: I run npx cypress run in an official Docker image with browsers. In GitLab it is a job in .gitlab-ci.yml, in Jenkins a stage in the Jenkinsfile. I take secrets from CI/CD variables or credentials and keep screenshots as artifacts. Middle/Senior: The steps are the same in all systems, only the syntax changes: a cache by lock file, waiting for the server, artifacts with always, JUnit for the tests tab. I do parallelism with several jobs and cypress-split or through Cloud, and add a messenger notification with a link to the report.
How to install and cache Cypress in CI?
Cypress consists of an npm package and a separate binary that lands in a global cache (on Linux ~/.cache/Cypress), not in node_modules. So in CI the binary folder is cached with a key based on the lock file, and dependencies are installed with npm ci. If the install was skipped, cypress install adds the binary and cypress verify checks that it runs.
Cypress · CI
node_modules is cached, yet every run still downloads Cypress. What exactly has to be cached?
The CI logs of every run show Cypress being downloaded although "the cache is set up". This is a typical mix-up: Cypress consists of two parts, and the cache is usually set up for the other one. The lesson sorts out what lies where, what to cache and what to do when the binary is missing.
How it works and why. Cypress consists of the cypress npm package and a binary (the application itself with the browser engine) that the package downloads during installation. The package lives in node_modules, and the binary in the user's global cache: on Linux it is ~/.cache/Cypress. The binary is not an npm package, so it lands neither in node_modules nor in the npm cache ~/.npm. The package's postinstall hook downloads the binary already during npm ci, and the binary is missing only when the hook was skipped and nothing was cached. So in CI you cache the binary folder, and not node_modules.
Three layers, three different caches
Figure 1. The npm cache does not contain the binary: that is why "the cache exists" and Cypress is still downloaded.
Dependencies.npm ci installs packages exactly by package-lock.json and fails if the lock file disagrees with package.json, so in CI it is more reliable than npm install. cypress-io/github-action picks the command by lock file itself.
The binary. Cache ~/.cache/Cypress, otherwise it is downloaded in every run. The cypress-io/github-action action caches the binary and, for npm and Yarn Classic, the package manager cache automatically.
Another cache location. The CYPRESS_CACHE_FOLDER variable sets the folder. It is needed in GitLab, where only paths inside the project can be cached, and in containers with a non-standard HOME.
Example: from a download in every run to a cache. Without a cache npm ci downloads the binary (hundreds of megabytes) every time and adds time to the run that has nothing to do with the tests. A manual cache in Actions looks like this:
The key depends on the lock file: updating Cypress changes the lock file, the key becomes new and a new version is downloaded. The cache step stands before npm ci: then postinstall sees a ready binary and does not download it a second time. Official Cypress advice: do not cache node_modules between builds and do not restore the cache with a key that is too loose (restore-keys with no tie to the version), because the cache then accumulates binaries of every version ever installed.
Limits and alternatives. The binary may be missing when the postinstall hook was skipped (for example by --ignore-scripts) and the cache is empty. Then the error at startup says Cypress is not installed, and diagnosis is simple:
npx cypress cache path # where the binary cache lives
npx cypress cache list # which versions are installed
npx cypress install # download the binary if it is missing
npx cypress verify # check that Cypress starts
cypress install downloads the binary of the right version and does nothing if it is already there, and cypress verify checks that Cypress starts. If the binary does not need to be downloaded (for example the image already has it), CYPRESS_INSTALL_BINARY can be set to 0. An alternative to caching: a ready Docker image with the binary inside (see the lesson on images), where there is no download at all.
Typical mistakes.
Caching node_modules and assuming the binary is cached too: it lies in another place.
Taking a cache by a key without the lock file or with a too loose restore-keys: old binaries pile up and the version may not match the package.
Installing dependencies with --ignore-scripts and forgetting cypress install: the binary is missing.
Using npm install instead of npm ci: the build depends on what changed on the registry.
Check yourself
The workflow caches node_modules but every run downloads Cypress. Why and what do you change?
Answer
The Cypress binary lies outside node_modules, in ~/.cache/Cypress, and is not part of the npm cache. Cache the binary folder with a key from the lock file (or use cypress-io/github-action).
After npm ci --ignore-scripts Cypress does not start because the binary is missing. Which command fixes it and why is it safe to repeat?
Answer
npx cypress install: it downloads the binary of the right version and does nothing if it is already there. Then npx cypress verify checks that it starts.
Related lessons: “How do you run Cypress in GitHub Actions?”, “Which Cypress Docker images to use in CI?”, “Cypress in Jenkins or GitLab CI”.
In the interview.Junior: npm ci also downloads the Cypress binary into the system cache through postinstall. In CI I cache the binary folder with a key from the lock file and do not cache node_modules. cypress install is needed only when the hook was skipped. Middle/Senior: I tell apart three layers: the npm cache, node_modules and the binary. For GitHub Actions cypress-io/github-action already does all of this, and in GitLab or containers I move the binary to CYPRESS_CACHE_FOLDER. An alternative to a cache: a cypress/included image where there is no download.
How to start the app before Cypress tests in CI?
The app is started in the background and the pipeline waits until its URL responds, since "the process is started" does not mean "the server listens". Without the wait the first cy.visit() fails with a connection error. The wait comes from wait-on, start-server-and-test or the start and wait-on fields of cypress-io/github-action, with a timeout. A health endpoint is a better target than the home page.
Cypress · CI
The server is started, yet the first test fails with a connection error. Why does "started" not mean "ready"?
Cypress tests open a live app, so in CI it has to be started before cypress run and given time to become ready. The difference between "the process is started" and "the server answers" looks small until the first cy.visit() fails on a slow machine. The lesson is about how to close that gap.
How it works and why. The command npm start & starts the process in the background and returns control at once. Before it listens on the port, the server still loads code, builds a bundle or connects to the database, and that takes from seconds to a minute. Cypress checks baseUrl at the start, and the first cy.visit() makes a request, so if the port is still closed, the test fails with a connection error. There is one cure: between start and tests put a step that blocks until the URL answers and has a timeout.
Start or wait
Wrong
npm start & cypress run
The background process only starts. Tests begin before the server listens on the port and the first visit fails with a connection error.
Right
start + wait-on
The waiting step blocks until the URL answers. Tests start only on a ready server, and a timeout stops a hang.
Figure 1. The difference is not whether the server is started but whether anyone checked that it answers.
wait-on blocks until the URL answers: start the server in the background, then npx wait-on http://localhost:3000, then Cypress.
start-server-and-test does it all in one call: it starts the server, waits for the URL, runs the test command and stops the server.
cypress-io/github-action has the fields start (the server command in the background), wait-on (the URL), wait-on-timeout (how many seconds to poll, 60 by default) and build for a build step.
Example: from a race to waiting. For any CI system a pair of commands or one call works:
npm start &
npx wait-on http://localhost:3000
npx cypress run
# or in one call
npx start-server-and-test start http://localhost:3000 "cypress run"
In GitHub Actions the action does the same. The build is moved to a separate step and the timeout is raised, because the first answer of a production build on a cold runner may take longer than the standard 60 seconds:
The start field is not meant for launching Cypress itself: it only brings up the server, and the process ends with the job. The address of the environment under test is baseUrl: it can be changed for one run without editing the file:
# environment address for one run, without editing the file
npx cypress run --config baseUrl=https://staging.example.org
# the same as an environment variable
CYPRESS_BASE_URL=https://staging.example.org npx cypress run
Limits and alternatives. Waiting for a URL proves the server answers but not that its dependencies are ready: the port may open before the database. If the app has a separate health endpoint, wait for it rather than for the home page. Another trap (with older Node and wait-on versions): localhost may resolve to the IPv6 address ::1 while the server listens only on 127.0.0.1, and then the wait never finishes. In that case give wait-on the explicit address 127.0.0.1 instead of localhost. For tests on a production build (build and start) the result is closer to reality than on a dev server, which builds code on the fly and answers the first requests more slowly. If the app is already deployed (staging), no server needs to be started: baseUrl is enough. In Playwright this role is played by webServer in the config with the command and url fields, so the waiting is built into the tool itself.
Typical mistakes.
npm start & npx cypress run with no waiting: the first tests fail, a re-run passes.
Raising defaultCommandTimeout instead of adding a wait for the server: a command timeout does not cure a closed port.
Not limiting the wait by a timeout: a hung server holds the job until the global limit.
Putting the Cypress command itself into start: the field is meant only for the server.
Check yourself
Cypress in CI fails on the first cy.visit with a connection error although npm start is in the logs. What do you check and fix?
Answer
Whether there is a readiness wait between starting the server and the tests. If not, I add wait-on or start-server-and-test (in Actions the start and wait-on fields) with a timeout, so tests run only after the URL answers.
wait-on http://localhost:3000 hangs until the timeout although the server runs and opens in a browser at 127.0.0.1. What could it be?
Answer
localhost resolves to IPv6 (::1) while the server listens only on IPv4. Give wait-on the explicit address 127.0.0.1 or make the server listen on both.
Related lessons: “How do you run Cypress in GitHub Actions?”, “Which Cypress Docker images to use in CI?”, “How do you configure different environments and environment variables?”.
In the interview.Junior: You cannot just start the server in the background and run the tests at once: you have to wait until the URL answers. wait-on and start-server-and-test exist for that, and in GitHub Actions cypress-io/github-action has the start and wait-on fields. I pass the environment address through baseUrl. Middle/Senior: I wait for a health endpoint rather than the home page, set a timeout, run a production build instead of a dev server and remember the IPv6 behaviour of localhost. For staging I start no server and only change baseUrl.
Which Cypress Docker images to use in CI?
Cypress has four families of official images: base, browsers, included and factory. The cypress/base image has no browsers, cypress/browsers adds Chrome, Firefox and Edge (the project controls the Cypress version), cypress/included has a fixed Cypress version, and cypress/factory builds a custom combination. The tag is pinned, because a short tag with a Node version can be updated without notice and the browser would change between runs.
Cypress · CI
The same test behaves differently in CI and locally. Could the browser in the image be to blame?
A test is green on a laptop and red in CI, and the only difference is the Chrome version or system libraries. The image the run happens in is part of the test environment, and choosing it decides whether it is reproducible. The lesson covers which official Cypress images exist, how they differ and how to pin them.
How it works and why. Cypress supports four families of official images: three ready-made ones are built on each other, and the fourth builds an image for your own versions. All of them remove the work of installing browsers and system libraries that you would otherwise write in every pipeline. The difference is what is already inside and who is responsible for the Cypress version.
Images built on each other
Figure 1. Each level adds a layer: from Node to a ready Cypress. cypress/factory stands apart and is built from your versions.
Image
What is inside
When to take it
cypress/base
Node and system dependencies, no browsers
Built-in Electron or your own browsers
cypress/browsers
+ Chrome, Firefox, Edge; Cypress from the project
The Cypress version is led by package.json
cypress/included
+ Cypress of a fixed version, globally
A ready image with no package installation
cypress/factory
A base OS, you choose the versions
Your own combination of Node, Cypress and browsers
cypress/base has no browsers, so it fits the built-in Electron (deprecated as a test browser in Cypress 16) or cases where the browser is installed separately. cypress/browsers adds Chrome, Firefox and Edge (for Linux/amd64), and Cypress is installed from the project through npm ci, so the version is set by package.json. cypress/included has a fixed Cypress version installed globally: the project does not need to install the package, but the version in the image and the version in the project can drift apart.
Example: an image in GitHub Actions. The image is set by the container field in the job. This works only on Linux runners. The container runs as root by default; the documentation advises options: --user 1001 to avoid permission problems (as root in GitHub Actions Firefox fails: Cypress does not detect versions below 138, and 138 and later hang):
In GitLab CI the image is set with the image: key, in Jenkins with a Docker agent in the Jenkinsfile. The same image can be started locally to reproduce a CI failure:
# reproduce the run locally in the same image
docker run -it -v $PWD:/e2e -w /e2e cypress/included:<tag>
Limits and alternatives. Pin the image tag. A short tag with the Node version (cypress/browsers:24.22.1) can be updated without warning, so to keep the browser from changing between runs, take a frozen tag with browser versions of the form node-…-chrome-…-ff-…-edge-…. A single image for all parallel jobs aligns the browser versions. An image with browsers is large, and downloading it is part of the run time, so on self-hosted runners it is cached. Alternatives to images: install browsers yourself on the runner (slower and less reproducible) or build your own image through cypress/factory when a non-standard combination is needed. In Playwright the same approach is provided by the official image mcr.microsoft.com/playwright.
Typical mistakes.
Taking the latest tag or a short Node tag: the browser changes between runs and a test suddenly fails with no code change.
Taking cypress/included and also installing the package in the project: the versions drift apart and it is unclear which one runs.
Using container on a Windows or macOS runner in GitHub Actions: it is supported only on Linux.
Leaving root in the container unchecked: some tools and older browsers behave differently as root.
Check yourself
A test suddenly started failing in CI with no code change, and the workflow image is cypress/browsers:24.22.1. Which cause do you check first?
Answer
The short tag may have been updated without warning, so the browser version changed. Pin a frozen tag with the Node, Chrome, Firefox and Edge versions and compare the browser version in the logs of the two runs.
How does cypress/browsers differ from cypress/included regarding the Cypress version?
Answer
In browsers Cypress is installed from the project through npm ci, so package.json sets the version. In included a fixed version is already installed globally and it may drift from the version in the project.
Related lessons: “How to install and cache Cypress in CI?”, “How do you run Cypress in GitHub Actions?”, “Cypress in Jenkins or GitLab CI”.
In the interview.Junior: I take cypress/browsers when Chrome or Firefox is needed and the project leads the Cypress version, and cypress/included if I want an image with Cypress already installed. cypress/base has no browsers. Middle/Senior: I take a frozen tag with browser versions so the browser does not change between runs, and one image for all parallel jobs. In Actions that is container on Linux only, with --user 1001. I run the same image locally to reproduce a failure.