What hooks does Cypress have and how do they work?
Cypress inherits its hooks from Mocha: before and after run once per block, beforeEach and afterEach around every test. Hooks of an outer describe wrap those of an inner one: beforeEach goes from outer to inner, afterEach in reverse. State is prepared in beforeEach, because afterEach does not run when the run is interrupted, and a failing hook makes Mocha skip the rest of the block.
Cypress · Practice and details
A run was stopped mid-test and the next one starts with dirty state. Why does cleanup in afterEach not save you?
The cart still has items from the previous test, and the new «empty cart» test fails. The cause is not the test itself but where the cleanup lives: it was in afterEach, and the run was interrupted. This lesson covers Cypress hooks: which ones exist, in what order they run, and where to put setup and cleanup so state does not leak between tests.
How it works and why
Cypress inherits hooks from Mocha. before runs once before all tests of a block, beforeEach before every test, afterEach after every test, after once after all of them. Hooks of an outer describe wrap those of an inner one: beforeEach goes from outer to inner, afterEach the other way. Hooks in cypress/support/e2e.ts belong to the root of every spec and apply to every test.
Where to clean up state
risky
afterEach
Does not run if the run is stopped mid-test. The next run starts with leftovers.
reliable
beforeEach
Every test guarantees its own starting state, however the previous one ended.
Figure 1. Cleaning before a test does not depend on how the previous one ended.
This is why the Cypress team advises preparing state before a test rather than cleaning after it. There is a second reason: when a test fails you want to see the app in the state it failed in (snapshot, video, an open browser in cypress open), and afterEach would change it. Separately from hooks, testIsolation (on by default since Cypress 12) clears cookies, localStorage, sessionStorage and opens a blank page before every test. It does not touch data on the server: the test prepares that itself.
Example: before → after
Before: the cart is cleaned in afterEach, and an interrupted run leaves an item on the server.
After: the test guarantees its own starting state, independent of the previous one.
describe('Cart', () => {
beforeEach(() => {
cy.request('DELETE', '/api/cart'); // clean state BEFORE the test
cy.login();
cy.visit('/cart');
});
it('empty cart', () => {
cy.contains('Your cart is empty').should('be.visible');
});
});
Resetting through the API is faster and more stable than clicking through the UI, and the login is worth moving into cy.session so it is not repeated for every test.
Limits and alternatives
If a hook fails, Mocha skips the remaining tests of the block: one failure in beforeEach becomes a dozen «skipped» tests. Keep hooks simple and reliable.
A before that fills the database is a trap: with testIsolation the browser state resets between tests, while server data stays and tests can change it. Prepare whatever a test mutates in beforeEach.
Playwright has the same hooks (test.beforeEach, test.afterAll…), but setup and teardown usually live in fixtures: the code after await use() runs even when the test fails.
Common mistakes
Cleanup in afterEach: when the run is aborted the state stays and the next run starts from leftovers.
An arrow function where Mocha's this is needed (context, aliases via this.alias): with =>this is different. Use a regular function for aliases.
A global beforeEach with a login in support/e2e.ts: it also runs for tests that do not need a login and adds seconds to each.
Check yourself
A test with afterEach cleanup was interrupted mid-run. What happens to the next run and how do you fix it?
Answer
afterEach did not run, so the data (an item in the cart) stays on the server and the next test starts with it. Fix: move the reset to beforeEach (ideally via the API) so each test guarantees its own starting state.
In what order do the hooks run if there is a beforeEach in support/e2e.ts, in an outer describe and in a nested one?
Answer
From the root to the deepest: first support, then the outer describe, then the nested one, and only then the test. afterEach hooks run in reverse.
Related lessons: “What types of assertions does Cypress support?”, “How do you control the order in which specs run?”, “How is the Cypress architecture built under the hood?”.
In an interview.Junior: Hooks come from Mocha: before and after run once per block, beforeEach and afterEach for every test. Middle/Senior: I do setup and cleanup of state in beforeEach, because afterEach does not run when a run is aborted. I reset data through the API, move the login into cy.session, and remember testIsolation: browser state resets by itself, server state does not. In Playwright fixtures do this, and the code after use() always runs.
What types of assertions does Cypress support?
Cypress bundles Chai (BDD and TDD), Chai-jQuery and Sinon-Chai, used implicitly through should or explicitly through expect. An implicit .should() retries together with its query until it passes or times out, while an explicit expect inside .then() runs once. Only .should(callback) retries the whole function, so for a changing DOM use should.
Cypress · Practice and details
The same element: should waits, expect inside then does not. Why?
A test checks the cart counter. Written as .should('have.text', '3') it passes steadily, written as .then(($el) => expect($el.text()).to.eq('3')) it sometimes fails: the value is still updating. Both «check the text»; the difference is whether Cypress repeats the check. This lesson lays out the assertion libraries bundled with Cypress and the two ways to call them.
How it works and why
Cypress ships with several libraries, and their assertions are available through one syntax:
Chai-jQuery: DOM state: be.visible, have.class, have.text, be.checked.
Sinon-Chai: spies and stubs (cy.spy, cy.stub): be.called, calledWith.
Two ways to call them. Implicit: .should() and .and() attach to the previous query command. Cypress repeats the query and the assertion together until it passes or the timeout (defaultCommandTimeout, 4 s) expires. Explicit: expect or assert in test code. Inside .then() it runs once on whatever is already there, with no retries. Only .should(callback) repeats the whole function, so explicit expect calls inside it are retried too.
Implicit and explicit assertion
retried
.should(...)
The query and the assertion repeat until success or timeout.
once
expect у .then
Takes the value at this moment: if it has not updated yet, the test fails.
Figure 1. Only what sits in a should chain (or in should(cb)) is retried.
Example: before → after
// before: one attempt, flaky
cy.get('[data-cy=cart-count]').then(($el) => {
expect($el.text()).to.eq('3');
});
// after: retried
cy.get('[data-cy=cart-count]').should('have.text', '3');
// several conditions at once: the whole function is repeated
cy.get('[data-cy=row]').should(($rows) => {
expect($rows).to.have.length.greaterThan(2);
expect($rows.first()).to.contain.text('Rex');
});
The function in should(cb) must be pure: no clicks, requests or variable mutations, because it runs as many times as needed to pass.
Limits and alternatives
The chain of queries before the assertion is retried: the whole chain (get, find, filter) is recomputed from the first query, but actions (click, type) are not repeated.
Negative assertions: should('not.exist') passes when the element is not in the DOM, while should('not.be.visible') on a missing element fails (since Cypress 6). To check that a spinner is gone use not.exist; not.be.visible fits an element that stays in the DOM but is hidden.
For one slow spot raise the timeout of that command, not the global one: cy.get('[data-cy=report]', { timeout: 15000 }).should('be.visible'). The timeout belongs to the query, and the assertion after it uses it.
A value that is not from the DOM (an API response, a variable) has nothing to retry: cy.request(...).its('status').should('eq', 200) or .then with expect.
In Playwright the analogue is web-first assertions await expect(locator).toHaveText(): they retry too, while a manual expect(await locator.textContent()) does not.
Common mistakes
An explicit expect inside .then for a changing DOM: the test is flaky. Replace with should.
Side effects in should(cb) (a click, a counter): the function runs several times.
cy.wait(1000) instead of an assertion: a fixed pause is both slower and still flaky.
Check yourself
Why is .then(($el) => expect($el.text()).to.eq('3')) flakier than .should('have.text', '3')?
Answer
then runs once with whatever is in the DOM already, while should repeats the query and the assertion until success or timeout (4 s by default), so it waits for the update.
When is an expect inside a callback retried after all?
Answer
When the callback is passed to .should(cb): Cypress repeats the whole function until no expect throws.
Related lessons: “What hooks does Cypress have and how do they work?”, “How do you work with URLs, navigation and browser history?”, “How do you debug tests in Cypress?”.
In an interview.Junior: Cypress uses Chai (BDD and TDD), Chai-jQuery for DOM state and Sinon-Chai for spies and stubs. Middle/Senior: More important than the list is the difference between implicit assertions via should, which retry together with the query, and an explicit expect in then, which runs once. For several conditions I use should(cb) without side effects. It is the same principle as web-first assertions in Playwright.
How do you work with Shadow DOM?
Cypress does not see inside a shadow root because Shadow DOM encapsulates the subtree and cy.get works like querySelector, stopping at that boundary. There are two ways across: the .shadow() command on the host, after which find and assertions work, or the includeShadowDom: true option on a command or in the config. The option widens queries, so keep selectors narrow. A closed shadow root is unreachable by design.
Cypress · Practice and details
cy.get('[data-cy=pay]') finds the button in DevTools but not in the test. Where is it?
A payment widget is built as a web component: the button is in DevTools, but cy.get('[data-cy=pay]') reports «Timed out retrying: Expected to find element». The button lives inside a shadow root, and a normal selector query does not enter it. This lesson explains why and how to get around it.
How it works and why
Shadow DOM encapsulates a subtree: styles and selectors from outside do not see it, and neither does document.querySelector. This is a deliberate platform design: a component should not leak into the page. cy.get works like querySelector, so by default it stops at the shadow root boundary. Cypress offers two ways across.
Two ways into a shadow root
targeted
.shadow()
The command enters the shadow root of exactly this element; then an ordinary find.
global
includeShadowDom
An option in the config (or in command options): queries pass through every shadow boundary.
Figure 1. Both ways are equally valid, the choice depends on how many components there are.
Reading the error: the element is in DevTools, but get cannot see it
AssertionError: 1Timed out retrying after 4000ms: 2Expected to find element: [data-cy=pay], 3but never found it.
What:get kept retrying the search for 4 seconds. This is not a broken command, it is the result of the wait.
What it looked for: an ordinary CSS selector, like querySelector. The same lookup in the DevTools console would find nothing too.
What is not said: the cause. The message is the same for a missing button and for a button inside a shadow root, so look at the DOM instead of adding waits.
What to do
If the Elements panel shows the button inside #shadow-root, step into it: cy.get('payment-widget').shadow().find('[data-cy=pay]').
Figure 2. The real error text: the numbers lead to the explanations.
Example: before → after
// before: not found, the button is in a shadow root
cy.get('[data-cy=pay]').click();
// after, targeted
cy.get('payment-widget').shadow().find('[data-cy=pay]').click();
// or once through a command option
cy.get('[data-cy=pay]', { includeShadowDom: true }).click();
// cypress.config.tsexportdefaultdefineConfig({
e2e: { includeShadowDom: true }, // globally for all queries
});
After .shadow() Cypress treats the content as an ordinary subtree: find, contains and assertions retry as usual. Nested components are walked in a chain: .shadow().find('inner-el').shadow().find(...).
Limits and alternatives
includeShadowDom: true is convenient when there are many shadow components, but queries become wider: a selector may match an element deep inside someone else's component. Narrow selectors (data-cy) reduce that risk.
This is about an open shadow root. A closed one (mode: 'closed') is by design unreachable to outside code, so for it agree test hooks (data-cy on the host itself, a separate build mode) with the developers.
cy.contains also enters a shadow root only with the option: cy.contains('Pay', { includeShadowDom: true }). The option applies to a single command, so a few places do not need the global setting.
Nested components and slots: content passed into a <slot> physically lives in the host light DOM, so cy.get finds it without .shadow(). You only need to enter the shadow root for elements the component creates itself.
In Playwright locators (getByRole, CSS) pierce open Shadow DOM by default; nothing to enable.
Common mistakes
Raising the timeout or adding cy.wait when an element «is not found»: the cause is the shadow boundary, not timing.
Calling .shadow() on an element without a shadow root: the command fails. First make sure it is a custom-element host.
Enabling includeShadowDom «just in case» and not noticing that old selectors now match duplicates.
Check yourself
An element is visible in DevTools but cy.get times out. What is the first hypothesis and how do you check it?
Answer
The element is in a shadow root. In DevTools it sits under a #shadow-root node. Check with cy.get(host).shadow().find(...) or { includeShadowDom: true }.
When is .shadow() better and when the global option?
Answer
.shadow() for a few places, where it is visible in code. The global option when the app is almost entirely web components and .shadow() would be needed everywhere.
Related lessons: “How do you do hover and drag-and-drop?”, “What types of assertions does Cypress support?”, “What do the project structure and the Cypress config look like?”.
In an interview.Junior: By default Cypress does not see shadow root content. I enter it with the shadow() command. Middle/Senior: If there are many Shadow DOM components I enable includeShadowDom in the config, but keep selectors narrow. Closed shadow roots are unreachable by design, which needs an agreement with development. In Playwright open Shadow DOM works with no setup.
How do you do hover and drag-and-drop?
Cypress has no native hover() because it fires synthetic JS events, while the CSS :hover pseudo-class depends on the real OS cursor. So .trigger('mouseover') runs handlers but does not open a menu held open only by CSS. For a real hover use the cypress-real-events plugin, and HTML5 drag-and-drop needs a chain of events with dataTransfer. Dropping a file onto a zone is covered by selectFile.
Cypress · Practice and details
A menu opens on hover, and the test «hovers» and sees nothing. What is wrong?
The menu has a rule .menu:hover .submenu { display: block }. The test calls .trigger('mouseover') and the submenu stays hidden. Same with dragging a card between columns: the events fire, the card does not move. Cypress has no native hover(), and the reason explains what to do.
How it works and why
Cypress runs inside the page and fires synthetic DOM events through JavaScript. mouseover handlers run, but the CSS :hover pseudo-class depends on the real operating-system cursor, which a synthetic event does not set. So .trigger('mouseover') runs JS logic but does not show a menu held open only by CSS. Drag-and-drop on the HTML5 API (draggable) also needs a chain of events with a dataTransfer object, while pointer-event libraries expect their own coordinates and sequence.
Synthetic event and real cursor
not always enough
trigger('mouseover')
A JS event in the page. CSS :hover is not switched on.
works
realHover()
The cypress-real-events plugin sends real browser events through the debugging protocol, so :hover applies.
Figure 1. The plugin works through the browser debugging protocol; see the plugin README for supported browsers.
Example: before → after
// before: a JS event, the CSS menu did not open
cy.get('[data-cy=menu]').trigger('mouseover');
cy.get('[data-cy=submenu]').should('be.visible'); // fails// option 1: the cypress-real-events plugin
cy.get('[data-cy=menu]').realHover();
cy.get('[data-cy=submenu]').should('be.visible');
// option 2: show the element directly (a workaround, not a hover check)
cy.get('[data-cy=submenu]').invoke('show').should('be.visible');
Option 2 only proves the submenu can be shown, not that it appears on hover. For the hover itself you need option 1.
For libraries built on mouse events you need the sequence mousedown → mousemove with coordinates → mouseup (pointer-event libraries need pointerdown → pointermove → pointerup: trigger dispatches only the event you name), often with several intermediate mousemove events. It is easy to lose hours here: a ready plugin or real events are usually faster.
The cypress-real-events plugin sends events through the browser debugging protocol, so it works only in Chromium-based browsers (the README says Firefox is not supported): before building a suite on it, check your CI browsers.
Limits and alternatives
Dropping a file onto a drop zone does not need trigger: cy.get(...).selectFile('file.pdf', { action: 'drag-drop' }).
A hover that only shows a tooltip can often be covered by a unit or component test, and e2e checks the end effect.
Playwright has it built in through real browser events: locator.hover() and locator.dragTo(target).
Common mistakes
Believing trigger('mouseover') equals hovering: for a CSS menu it is useless.
Forgetting dataTransfer in HTML5 drag-and-drop: drop fires without data and the library logic gets nothing.
Hiding the problem with { force: true } or invoke('show') and never checking real user behaviour.
Check yourself
Why does trigger('mouseover') not open a menu driven by CSS :hover?
Answer
It is a synthetic JS event: it runs handlers but does not change the cursor state that :hover depends on. Real events (cypress-real-events) are needed.
What does invoke('show') verify instead of hover and what does it not verify?
Answer
It forces the element to show and lets you check content or click the submenu. It does not prove that the menu opens on hover: that link stays unverified.
Related lessons: “How do you work with Shadow DOM?”, “How do you debug tests in Cypress?”, “What types of assertions does Cypress support?”.
In an interview.Junior: Cypress has no native hover: trigger('mouseover') runs JS handlers but not CSS :hover. I do drag-and-drop with trigger and the needed mouse events. Middle/Senior:trigger only fires synthetic JS events, so it does not switch on a real CSS hover. For that I use cypress-real-events, and for HTML5 drag I add dataTransfer. In Playwright hover() and dragTo() are built in.
How does cy.exec differ from cy.task?
cy.exec ran a shell command and cy.task calls a Node function from setupNodeEvents, but Cypress 16 removed cy.exec in favour of cy.task. A task returns its result to the test, takes one serialised argument and must not return undefined, so null means nothing. Shell commands now run inside a task through execFileSync with an argument array, which bypasses the shell, and calling cy.exec throws.
Cypress · Practice and details
A script must seed the database before a test. cy.exec or cy.task, and what changed in Cypress 16?
The test needs a database with known data, and the project already has a seed script. Browser test code cannot start a process or talk to Postgres: everything outside the browser runs in the Cypress Node process. Two commands existed for this, cy.exec and cy.task.
Important: in Cypress 16 cy.exec() was removed and calling it throws. Shell commands are now run inside cy.task() through child_process.execFileSync() with an argument array: the cy.task docs recommend this because an argument array avoids the shell, so quoting and PATH lookup behave the same on every platform. The comparison with cy.exec remains in interview questions and in older projects.
How it works and why
Both commands step out of the browser into Node. cy.exec('command') ran a shell command and yielded { exitCode, stdout, stderr } (named code before Cypress 15); a non-zero exit code failed the test by default (failOnNonZeroExit: false turned that off). cy.task('name', arg) calls a Node function registered in setupNodeEvents: it receives one serialisable argument, returns a value (or a promise) and must not return undefined, or the command fails; to return «nothing», return null.
cy.exec and cy.task
cy.exec (≤ 15)
shell command
A ready script or CLI. Yields code, stdout, stderr. Removed in Cypress 16.
cy.task
Node function
Your own logic: a DB query, files, data generation. Returns a value to the test. Works in 16 too.
Figure 1. After exec was removed its role is played by task with execFileSync.
Example: before → after
// before (up to 15): a shell command in the test
cy.exec('node scripts/seed.js').its('exitCode').should('eq', 0);
// cypress.config.tsimport { defineConfig } from'cypress';
import { execFileSync } from'node:child_process';
exportdefaultdefineConfig({
e2e: {
setupNodeEvents(on) {
on('task', {
seedDb() {
// argument array: no shellexecFileSync('node', ['scripts/seed.js'], { stdio: 'pipe' });
returnnull; // a task cannot return undefined
},
});
},
},
});
// in the test
cy.task('seedDb');
Note node scripts/seed.js instead of npm run db:seed: on Windows npm is npm.cmd, and execFileSync cannot launch .cmd files without a shell, so running node directly is safer for scripts. If the function needs data, pass it as the second argument cy.task('name', arg) and read the result like any other subject.
A task can be asynchronous and return data to the test: there is one argument, so several values go in an object that the task destructures.
// cypress.config.tson('task', {
asyncfindOrders({ userId, status }: { userId: number; status: string }) {
const rows = await db.query('select * from orders where user_id = $1 and status = $2', [userId, status]);
return rows; // a serialised array reaches the test
},
});
// in the test; { timeout } raises the limit of this command only
cy.task('findOrders', { userId: 7, status: 'paid' }, { timeout: 120000 }).should('have.length', 2);
Limits and alternatives
Tasks run in a Node process with the rights of the user who started Cypress: never pass unchecked input from a test to execFileSync.
There is a default timeout (taskTimeout, 60 s); long operations are better moved to before:run or a separate CI step.
Resetting data is often faster and cleaner through the application API (cy.request) than through a shell.
Playwright needs no analogue: the test already runs in Node, so child_process or a DB client is called directly.
Common mistakes
A task with no return: Cypress complains that it returned nothing. Return null.
Building a shell string from test data: injection risk and OS differences. An argument array solves both.
Pulling heavy dependencies into setupNodeEvents at top level: they load at every config start.
Check yourself
A test calls cy.task('seedDb') and the function returns nothing. What happens and how do you fix it?
Answer
Cypress throws an error that the task returned undefined. Fix: return null (or return a useful value).
Why does a task run execFileSync('node', ['scripts/seed.js']) and not a command string?
Answer
An argument array does not go through a shell: no quote parsing, no injection, no differences between OS shells.
Related lessons: “What Node events does Cypress have, for example after:run?”, “What hooks does Cypress have and how do they work?”, “How is the Cypress architecture built under the hood?”.
In an interview.Junior: Both commands run code outside the browser, in Node. cy.task calls a Node function from the config and returns data to the test, for example a database query. Middle/Senior: In Cypress 16 cy.exec was removed, so I run shell commands from cy.task through execFileSync with an argument array. A task must not return undefined, and for data I prefer the application API.
What Node events does Cypress have, for example after:run?
Cypress Node events are run-level hooks, not test hooks, registered in setupNodeEvents and run in Node, not in the browser. The main ones are before:run and after:run around the whole run, before:spec and after:spec around each spec file, before:browser:launch for browser flags and after:screenshot for processing a screenshot. They are used, for example, to delete videos of passed specs.
Cypress · Practice and details
You want videos of failed tests but not of passed ones. Where is that configured: in the test or in the config?
Some things do not belong to any test: the summary of a whole run, deleting unneeded videos, browser launch flags. For these Cypress has Node events: hooks at the level of a run, not a test. The lesson covers which they are, when they fire and how they differ from beforeEach.
How it works and why
Test hooks (beforeEach) run in the browser. Node events are registered in setupNodeEvents(on, config) and run in the Cypress Node process, which has access to the file system, the network and the full data of the run. That is by design: the browser is isolated, and only Node knows about the «run» as a whole.
Who fires when
run and spec
before:run → before:spec → after:spec → after:run
Around the whole run and every file. Only in cypress run.
targeted
before:browser:launch, after:screenshot
Browser setup before launch, handling each screenshot.
Figure 1. The events before:run, after:run, before:spec, after:spec work in run mode.
before:run / after:run: before and after the whole cypress run; after:run receives the results.
before:spec / after:spec: around every spec file; after:spec receives that file's results.
on('after:run', (results) => {
// after a failed launch an error arrives instead of totalsif ('totalFailed'in results) {
console.log('Failed tests:', results.totalFailed);
}
});
The check 'totalFailed' in results is needed because when the launch fails (for example, no specs found) an object with an error message arrives instead of totals. Videos have been off by default since Cypress 13, so video: true must be enabled deliberately.
import fs from'node:fs';
// browser flags before launchon('before:browser:launch', (browser, launchOptions) => {
if (browser.family === 'chromium' && browser.name !== 'electron') {
launchOptions.args.push('--window-size=1400,900');
}
return launchOptions; // return the changed options
});
// rename a screenshoton('after:screenshot', (details) => {
const newPath = details.path.replace('.png', '-ci.png');
fs.renameSync(details.path, newPath); // the handler moves the file itselfreturn { path: newPath };
});
before:browser:launch must return launchOptions, otherwise the changes are not applied. after:screenshot does not rename the file itself: the handler moves it (for example with fs.renameSync) and returns the new path so Cypress knows where the file now is.
Limits and alternatives
Events do not behave in cypress open the way they do in run mode: check report and notification logic in cypress run.
For one event usually a single handler applies: if several plugins register the same event, merge them explicitly, otherwise a later registration replaces the earlier one (on('task') is the exception: Cypress merges task objects).
Playwright analogues: globalSetup / globalTeardown in the config or a setup project; run totals in a custom reporter via onEnd.
Common mistakes
Registering before:run where cleanup before every test is needed: these are different levels, tests have beforeEach.
Writing after:run code that assumes results always holds totals.
Deleting a file without checking it exists: the video may not have been created.
Check yourself
How does after:spec differ from after in a spec?
Answer
after runs in the browser, in the test context. after:spec runs in Node after the file finishes and receives its results, video and stats.
Why does the after:run example check 'totalFailed' in results?
Answer
If the launch did not happen, an object with an error arrives instead of totals, and it has no such field.
Related lessons: “How does cy.exec differ from cy.task?”, “What hooks does Cypress have and how do they work?”, “What do the project structure and the Cypress config look like?”.
In an interview.Junior: These are run-level events registered in setupNodeEvents: after:run fires after the whole run and receives the results. Middle/Senior: I use after:spec to delete videos of passed specs and before:browser:launch for browser flags. I remember these events run in Node, not in the browser, and that a handler for one event must be merged across plugins.
How do you control the order in which specs run?
The order of spec files is not guaranteed, so tests must be independent, and specPattern and --spec only select files. Inside one file tests run top to bottom. Order dependence breaks under parallel runs, retries and re-running a single file. Shared setup goes into beforeEach, an API call or cy.session, not into a separate "test".
Cypress · Practice and details
The checkout test passes only after the login test. Is that a problem or normal?
A typical question: «How do you set the order in which specs run?». Behind it is another situation: checkout.cy.ts works only when login.cy.ts ran before it, because that one created a user or a session. While the run is sequential, everything is green. The first parallel run, retry or single-file run breaks such a suite. The lesson covers what you can and should not do about order.
How it works and why
Which files run is set by specPattern (a string or an array of globs in the config) and --spec in the CLI. The documentation describes them as file selection. It gives no contract about the order between files, so tests must not be built on it. Inside one file the order is reliable: tests run top to bottom in declaration order (this is how Mocha works).
Why depending on order hurts. First, testIsolation clears browser state between tests, so a «login from the previous test» will not survive anyway. Second, retries (retries) rerun only the failed test, without the earlier ones. Third, parallel runs in CI spread specs across machines in no fixed order. Fourth, rerunning a single broken test never passes if it depends on a neighbour.
Order dependency and independent tests
fragile
Test B needs test A
Breaks under parallelism, retries, a single run.
robust
Each test prepares its own data
The user or session is created through the API before the test.
Figure 1. Independent tests give both parallelism and isolated reruns.
Example: before → after
// before: checkout relies on login.cy.ts// login.cy.tsit('creates a user and logs in', () => { /* ... */ });
// checkout.cy.tsit('places an order', () => {
cy.visit('/checkout'); // will not work without login
});
// after: each test prepares what it needsbeforeEach(() => {
cy.request('POST', '/api/test/users', { email: 'qa@example.com' });
cy.session('qa', () => {
cy.request('POST', '/api/login', { email: 'qa@example.com' });
});
cy.visit('/checkout');
});
To run only part of the suite use file selection: npx cypress run --spec "cypress/e2e/checkout/**". If a scenario really consists of steps that make no sense separately (a long wizard form), write one test with several steps and an explanation in its name, rather than several dependent ones.
A login shared across files comes from cy.session with the cacheAcrossSpecs: true option: the first file that needs the session creates it and the others reuse the cache, so no file depends on something having run earlier. Independence is checked by running each file alone, for example in a CI loop.
# each spec alone: one that depends on a neighbour will fail
fail=0
for f in cypress/e2e/*.cy.ts; do npx cypress run --spec "$f" || { echo "FAILED: $f"; fail=1; }; done
exit $fail
Limits and alternatives
Top-to-bottom order inside a file can serve readability but not as a dependency: it.only or a retry will break it.
Shared setup goes into beforeEach, cy.session or an API request, not into a separate «test».
In Playwright the principle is the same: tests are independent and workers spread files arbitrarily; for a deliberately sequential scenario there is test.describe.configure({ mode: 'serial' }), but it is an exception.
Common mistakes
Relying on spec order and not noticing the problem until parallel runs are enabled.
Passing data between tests through a variable or a file: in a retry or a single run it is not there.
Naming files 01-login.cy.ts, 02-order.cy.ts instead of removing the dependency: it only masks it.
Check yourself
The suite is green when sequential and red when parallel. What is the most likely cause and how do you check?
Answer
Tests depend on order or on shared server state. Check: run one «red» file alone through --spec; if it fails on its own, the dependency is confirmed.
Why does retries not save a dependent test?
Answer
A retry repeats only the failed test in a clean state (testIsolation) without the earlier ones. It does not restore data or a session from a neighbouring test.
Related lessons: “What hooks does Cypress have and how do they work?”, “How does cy.exec differ from cy.task?”, “What do the project structure and the Cypress config look like?”.
In an interview.Junior: The files to run are chosen with specPattern and --spec, and inside a file tests go in declaration order. Middle/Senior: I do not build order between files into the logic: dependent tests break under parallel runs, retries and single reruns. I create data and the session through the API and cy.session in beforeEach.
Which browsers and operating systems does Cypress support?
Cypress runs tests in Chrome-family browsers (Chrome, Chromium, Chrome for Testing, Edge) and Firefox, with experimental WebKit support. WebKit is the Safari engine, not Safari itself. Real Safari on an iPhone, mobile browsers and native apps are out of reach; a mobile view is only emulated by window size. Real devices need a cloud device farm or Appium, and exact Node and OS versions come from the documentation.
Cypress · Practice and details
A client asks to «also check in Safari on an iPhone». What can Cypress do about it?
Choosing a tool comes down to «where will it run». Cypress runs tests in a real browser, but not in any browser. The lesson records what is supported, what is missing and how to talk about versions carefully.
How it works and why
Cypress runs inside the browser, so it needs the browser to let its agent start and to offer the debugging capabilities it uses. That is why support goes by families. The documentation names Chrome-family browsers (including Edge and Chrome for Testing) and Firefox, and adds WebKit as experimental support. The Chrome family includes Chrome, Chromium, Chrome for Testing and Edge. WebKit is enabled with a separate option and is the Safari engine, not Safari itself. Cypress bundles Electron, and it is what cypress run uses when no browser is given through --browser. Since Cypress 16 Electron is deprecated as a test browser and will be removed, so in CI name the browser explicitly.
What is in and what is out
supported
Browsers
Chrome family (including Edge), Firefox, WebKit (experimental), Electron (deprecated since 16).
not supported
Out of scope
Real Safari, Internet Explorer, Opera, mobile browsers and native apps.
Figure 1. A mobile layout is emulated by window size (cy.viewport), not by a mobile browser.
System requirements (per the Cypress install page, 2026-11): Windows 10 and 11, macOS 13.5 and newer, Linux (for example Ubuntu 22.04+, Debian 12+); Node.js 22.x, 24.x and 26+. Such minimums shift with every major release, so in an interview it is better to name the principle («current LTS Node versions and supported OSes») and say the exact numbers come from the documentation.
Example: before → after
Before: «Cypress will cover Safari on an iPhone too». After: an honest talk about coverage. Choosing a browser:
npx cypress run --browser chrome
npx cypress run --browser firefox
npx cypress run --browser edge
// a matrix of sizes (emulation, not a mobile browser)const sizes: Cypress.ViewportPreset[] = ['iphone-x', 'ipad-2', 'macbook-15'];
sizes.forEach((size) => {
it(`menu works on ${size}`, () => {
cy.viewport(size);
cy.visit('/');
cy.get('[data-cy=menu]').should('be.visible');
});
});
Takeaway for the client: Cypress covers Chrome, Edge, Firefox and (experimentally) WebKit and emulates a mobile layout, but real Safari on an iPhone needs another tool: a real-device cloud or Appium.
// a test for certain browsers onlyit('works in Firefox', { browser: 'firefox' }, () => { /* ... */ });
it('skips Firefox', { browser: '!firefox' }, () => { /* ... */ });
// branching in codeif (Cypress.browser.name === 'webkit') { /* ... */ }
# a browser matrix in CI (GitHub Actions)strategy:
matrix:
browser: [chrome, firefox, edge]
steps:
- run: npx cypress run --browser ${{ matrix.browser }}
For WebKit enable experimentalWebKitSupport: true in the config and install the playwright-webkit package; without it a WebKit run does not start.
Limits and alternatives
WebKit in Cypress ≠ Safari: the engine is the same but the shell, versions and OS behaviour differ. Experimental means a risk of instability.
Native mobile apps: Appium (or other mobile frameworks), not Cypress.
Playwright supports Chromium, Firefox and WebKit across the board, plus mobile device emulation, but also not native apps.
Common mistakes
Promising «Safari coverage» through the WebKit mode without the experimental caveat.
Quoting exact minimum Node or OS versions from memory: they change and are checked in the documentation.
Treating cy.viewport('iphone-x') as an iPhone check: it is only a window size.
Check yourself
What do you answer to «cover Safari on an iPhone with Cypress»?
Answer
Cypress can emulate the screen size and run WebKit experimentally, but that is not real Safari on a device. That needs a real-device farm or Appium.
How does the WebKit mode in Cypress differ from Safari?
Answer
It is the same engine but without the Safari shell, macOS and iOS specifics, and with experimental status.
Related lessons: “How is the Cypress architecture built under the hood?”, “How do you debug tests in Cypress?”, “What do the project structure and the Cypress config look like?”.
In an interview.Junior: Cypress works with Chrome-family browsers, including Edge, with Firefox and experimentally with WebKit. Middle/Senior: There is no real Safari, mobile browsers or native apps; that is an architectural limit. I emulate a mobile layout by window size and cover real devices with a device cloud or Appium. I take Node and OS versions from the documentation because they change.
How do you debug tests in Cypress?
Locally Cypress is debugged with time travel in the Command Log, cy.pause(), .debug() and DevTools, and in CI with artifacts. The Command Log stores a DOM snapshot for every command, so it shows the page before and after a step. In a headless run pause and debug do not help, so in CI you read the error text, screenshot, video, a log through cy.task and, with Cypress Cloud, Test Replay.
Cypress · Practice and details
The test is green locally and red in CI. Where do you start when you only have a log?
Locally you can look at the screen, in CI you have files and text. So Cypress has two sets of tools: interactive ones for cypress open and artifacts for cypress run. The lesson shows what to reach for and when.
How it works and why
The Test Runner records a DOM snapshot for every command, so the Command Log can show the page state before and after any step. This «time travel» is the main tool. The test runs in an ordinary browser, so DevTools work too: console, network, debugger.
Where to debug
locally
cypress open
Time travel, cy.pause(), .debug(), DevTools, a click on a command.
in CI
cypress run
Screenshots, video (if enabled), logs via cy.task, Test Replay in Cypress Cloud.
Figure 1. Locally you watch live, in CI you read artifacts.
Time-travel: hover a command in the Command Log to see the DOM snapshot at that moment.
cy.pause(): stops execution, then step through commands.
.debug(): sets a debugger and logs the current subject to the console (DevTools must be open).
Click on a command: prints details to the console: subject, elements, request and response.
cy.log() writes to the Command Log; cy.task('log', ...) prints to the CI terminal.
Example: before → after
Before: in CI «element not found» and no context. After: temporary observation points and a log to the terminal.
cy.get('[data-cy=total]').debug(); // subject in the console + debugger
cy.pause(); // stop, then step manually
cy.get('[data-cy=checkout]').click();
// a log to the CI terminal
cy.url().then((url) => cy.task('log', 'URL: ' + url));
// cypress.config.tssetupNodeEvents(on) {
on('task', {
log(message: string) {
console.log(message);
returnnull; // a task must return something
},
});
},
For CI you enable screenshots (by default Cypress takes them on failure in cypress run), video (video: true) and, with Cypress Cloud, Test Replay, where a test can be replayed with DOM and network. Cypress itself logs more with the DEBUG=cypress:* environment variable, but that is for problems with the tool, not with tests.
// your own debugger inside .then(): the subject is available as a parameter
cy.get('[data-cy=total]').then(($el) => {
debugger; // stops only when DevTools are open
});
// extra context on failureCypress.on('fail', (error, runnable) => {
error.message += '\n' + 'Test: ' + runnable.fullTitle();
throw error; // without the throw the test would not get the failed state
});
How to read a failed test in CI: first the error text (which command and what was expected), then the screenshot at the moment of failure, then the video to see what led up to it and, with Cypress Cloud, Test Replay with DOM and network. Each next artifact is slower to read, so stop once the cause is clear.
Limits and alternatives
cy.pause() and .debug() are of no use in a headless run: in CI they do not help and are removed before committing.
Snapshots in the Command Log are snapshots, not a live app: the state after a test can be inspected but the steps cannot be «replayed».
Playwright analogues: page.pause(), npx playwright test --debug with the inspector, UI mode (--ui) and Trace Viewer for CI.
Common mistakes
Leaving cy.pause() or .debug() in the code: in CI they do nothing but add noise.
Opening DevTools after .debug(): the stop has already passed, they had to be opened beforehand.
Debugging «by eye» in a single run instead of saving artifacts and reproducing the error.
Check yourself
A test fails only in CI and the team suggests adding cy.pause(). Why will that not help?
Answer
In CI the run is headless without an interactive Command Log, so a pause shows nothing. Artifacts are needed: screenshot, video, a log via cy.task or Test Replay.
How does .debug() differ from cy.log()?
Answer
.debug() stops in DevTools and prints the subject to the console, while cy.log() only writes a message to the Command Log.
Related lessons: “What types of assertions does Cypress support?”, “How do you work with URLs, navigation and browser history?”, “Which browsers and operating systems does Cypress support?”.
In an interview.Junior: Locally I use time travel in the Command Log, cy.pause for stepping and .debug() to inspect the subject in DevTools. Middle/Senior: In CI I look at screenshots, video, logs through cy.task and Test Replay. I tell interactive tools from artifacts. In Playwright the analogue is Trace Viewer.
How do you work with URLs, navigation and browser history?
URLs are read with cy.url() and cy.location(), history is moved with cy.go() and a page is refreshed with cy.reload(). Both URL commands retry together with their assertion and wait for navigation on their own, while go and reload run once. Write the check as an assertion, not a one-off read in .then, and prefer cy.location('pathname'), which does not depend on the host.
Cypress · Practice and details
After a click the test checks the address at once and fails, although the page opens a moment later. Why?
The «Statistics» button leads to /statistics?period=30d. The test checks the address right after the click. Sometimes it passes, sometimes not. It depends on how the check is written: with a retried assertion or a one-off read of the value. The lesson is about URLs, navigation and history in Cypress.
How it works and why
cy.url(): the full URL as a string.
cy.location(): an object with pathname, search, hash and other parts; cy.location('pathname') returns a single part. Convenient for checking parts separately.
cy.go('back') / cy.go('forward'): the «back» and «forward» buttons.
cy.reload(): reloads the page.
cy.url() and cy.location() are queries retried together with their assertions, so assertions on the URL wait for navigation themselves. cy.go() and cy.reload() are ordinary commands: they run once, and only the assertions after them are retried.
A retried query and a one-off read
retried
cy.location('pathname').should(...)
Waits until the timeout for the URL to become the right one.
once
cy.url().then(u => expect(u)...)
Reads the address at this moment: if navigation has not finished, it fails.
Figure 1. Retries come only from should chained to a query.
Reading the error: a URL check without a retry
AssertionError: 1expected 2'http://localhost:3000/dashboard' to include '/statistics'
What is missing: the “Timed out retrying after 4000ms” prefix. So the expect inside .then ran once and Cypress retried nothing.
What was read: the address of the old page. The click had just happened and the navigation had not finished.
What to do
Replace the one-time read with an assertion that retries: cy.location('pathname').should('eq', '/statistics').
Figure 2. The real error text: the numbers lead to the explanations.
Example: before → after
// before: a single read, flaky
cy.get('[data-cy=stats-link]').click();
cy.url().then((url) => {
expect(url).to.include('/statistics');
});
For parameters it is convenient to open the page with a qs object: cy.visit('/statistics', { qs: { period: '30d' } }). A full URL can be compared with the base: cy.url().should('eq', Cypress.config('baseUrl') + '/statistics'), but cy.location('pathname') does not depend on the host and is more reliable across environments.
// a page that answers 404, without failing the test at visit itself
cy.visit('/missing', { failOnStatusCode: false });
cy.contains('Page not found').should('be.visible');
// an SPA hash route
cy.location('hash').should('eq', '#/settings');
// wait for navigation through the network
cy.intercept('GET', '/api/stats*').as('stats');
cy.get('[data-cy=stats-link]').click();
cy.wait('@stats');
By default cy.visit fails on any response other than 2xx and 3xx, so an intentional error page needs failOnStatusCode: false. Hash routes do not reload the page; check them with cy.location('hash'). If the app still loads data after navigating, waiting for the response through a cy.intercept alias is more reliable than guessing from the URL.
Limits and alternatives
In SPAs navigation may not reload the page (history.pushState): the URL changes without a load event and cy.go() walks the app history. An assertion on the URL still works.
Going to another origin inside a test needs cy.origin(); without it Cypress blocks access to the other origin.
In Playwright: await expect(page).toHaveURL(/statistics/), page.goBack(), page.goForward(), page.reload().
Common mistakes
Reading the URL in .then and comparing with one expect: without a retry the test is flaky.
Checking the query string as a whole text (?a=1&b=2): the order of parameters may change. Prefer include for a single parameter.
Expecting cy.reload() to retry itself: it runs once, only the assertions after it are retried.
Check yourself
Why is cy.location('pathname') better than cy.url() for checking a page?
Answer
It does not depend on host and protocol, so it works the same locally, on staging and in production, and lets you check path and parameters separately.
What is retried in cy.go('back'); cy.url().should('include', '/dashboard')?
Answer
cy.go runs once. cy.url() is retried together with the should assertion until the URL is right or the timeout expires.
Related lessons: “What types of assertions does Cypress support?”, “How do you debug tests in Cypress?”, “How do you control the order in which specs run?”.
In an interview.Junior: For URLs there are cy.url and cy.location, for history cy.go back and forward, for refreshing cy.reload. Middle/Senior:cy.url and cy.location retry together with the assertion, so they wait for navigation, while go and reload run once. I check pathname and parameters separately and avoid one-off reads in then.