QA Interview Hub · Knowledge base · Quizzes · Українська

Cypress

Framework architecture

POM, commands, config, cy.task

How do you create a custom command and type it in TypeScript?

A custom command is registered with Cypress.Commands.add in the support file, and its type is added to the Cypress.Chainable interface for TypeScript. The body calls ordinary cy commands that go into the queue, so the command does not return a value synchronously or mix with async/await. Registration and type live separately: the file needs export {}, and tsconfig must include the support folder with the cypress types.

Cypress · Patterns and data

The same cy.get('[data-cy=…]') in fifty tests. Where do you hide it so TypeScript still autocompletes?

In a suite of fifty tests every test opens with five lines of login and the [data-cy="…"] selector is typed by hand hundreds of times. When the team renames the attribute, everything needs editing. A custom command gathers this code in one place and adds a new action to cy. This lesson covers how to register one, how to describe its type so the editor and tsc know about it, and where custom commands do harm.

How it works and why. Cypress does not run cy.get() immediately: every call puts a command in a queue, and the runner then walks the queue one by one, waiting and retrying. Cypress.Commands.add(name, fn) adds one more name to the same mechanism: inside fn you call ordinary cy commands, they join the queue too, and the result of the last one becomes the result of the new command. That is why a command does not return a value synchronously and does not use async/await: it describes what to enqueue.

There is a second half: types. The command exists at runtime, but cy.getByCy is unknown to the compiler until you extend the Cypress.Chainable interface (declaration merging). Both halves live in support files that Cypress loads before every spec (cypress/support/e2e.ts imports ./commands).

Three steps to make a command work

1. Cypress.Commands.addwhat it does at runtime2. interface Chainablewhat TypeScript knows about it3. import in support/e2e.tswithout it the spec has no command
Figure 1. Registration, type, loading: skip one step and the command is either missing or untyped.

Example: from repetition to a command. Before: every test repeats the same login through the form. Here and below we assume the app sets a session cookie after POST /api/auth/login.

beforeEach(() => {
  cy.visit('/login');
  cy.get('[data-cy="email"]').type('anna@example.com');
  cy.get('[data-cy="password"]').type('secret', { log: false });
  cy.get('[data-cy="submit"]').click();
  cy.url().should('include', '/dashboard');
});

After: two commands in commands.ts and the type declarations in the same file. TypeScript treats a file without import/export as a script, and declare global is only allowed in a module, so the export {} line is required.

// cypress/support/commands.ts
Cypress.Commands.add('getByCy', (id: string) => {
  return cy.get('[data-cy="' + id + '"]');
});

Cypress.Commands.add('login', (email: string, password: string) => {
  cy.session(email, () => {
    cy.request('POST', '/api/auth/login', { email, password });
  });
});

declare global {
  namespace Cypress {
    interface Chainable {
      getByCy(id: string): Chainable<JQuery<HTMLElement>>;
      login(email: string, password: string): Chainable<void>;
    }
  }
}
export {};

// the test
beforeEach(() => cy.login('anna@example.com', 'secret'));
it('shows the dashboard', () => {
  cy.visit('/dashboard');
  cy.getByCy('balance').should('be.visible');
});

Why this way. cy.session() caches cookies and storage after the first login and restores them in later tests, so the command is not only shorter but faster. getByCy returns the cy.get(...) chain, so .should() and .click() continue it as usual. The result type Chainable<JQuery<HTMLElement>> mirrors what cy.get itself returns: write Chainable<void> and the following calls lose their suggestions. For the editor to see the types, cypress/tsconfig.json needs "types": ["cypress"] and must include the support folder.

Related forms. A child command receives the previous result as subject when you pass the prevSubject option. An existing command can be wrapped with Cypress.Commands.overwrite, for example to add default options to visit.

Cypress.Commands.add('findByCy', { prevSubject: 'element' }, (subject, id: string) => {
  return cy.wrap(subject).find('[data-cy="' + id + '"]');
});

// in Chainable:
// findByCy(id: string): Chainable<JQuery<HTMLElement>>;
cy.getByCy('order-list').findByCy('row-1').click();

Limits and alternatives. A command is optional. A plain function that returns the chain works the same way, and the editor offers "go to definition" without type tricks. Commands pay off where you want an action "inside cy": login, getByCy. Inside a command you cannot mix async/await with the Cypress queue, and assertions buried in a command make a test unreadable. Playwright has no custom commands: fixtures from test.extend<MyFixtures>(), helpers and Page Object methods play their role.

Common mistakes.

  • Forgetting export {} or the import in support/e2e.ts: the type is "not found" or the command is missing at runtime.
  • Declaring the type but not registering the command: tsc is silent and the test fails with "cy.login is not a function".
  • Writing const el = cy.getByCy('x') and using el as a value: it is a queued step, not an element.
  • A ten-line command with conditions and assertions: the test looks simple and the logic is hidden.

Check yourself

The cy.login() command is registered, but tsc says "Property 'login' does not exist on type Chainable". What do you check?

Answer

Whether the method is declared in interface Chainable inside declare global { namespace Cypress }, whether the file has export {} (otherwise it is not a module), and whether the Cypress tsconfig includes the support folder with types: ["cypress"]. Registration in Commands.add does not affect types.

Why can't a command contain const res = await cy.request(...)?

Answer

cy.request returns not a Promise but a description of a step in the Cypress queue. await will not wait for it to run. You take the result in .then() or through an alias.

In an interview. Junior: I register custom commands with Cypress.Commands.add in support and add the type to the Chainable interface so TypeScript suggests the command. Typical examples are getByCy and login. Middle/Senior: A command queues steps in the Cypress queue, so it returns no value and does not mix with async/await. Types and implementation live apart, so I check both halves and the import in support. Where a plain function is enough I pick it, and in Playwright fixtures play this role.

Page Object or App Actions: which do you choose?

Page Object and App Actions solve different problems, so they are combined rather than chosen between. Page Object gathers a page's selectors and actions into a class and eases interface maintenance. App Actions prepare state directly through the API, cy.task or application functions, which makes the test faster and more stable. So state is prepared through the API, and the UI is used where it is the subject of the test.

Cypress · Patterns and data

The statistics page changed and forty tests broke. Should they have been written differently?

A test checks a chart on the statistics page, but to reach it, it logs in, creates five orders through a form and only then opens the report. When the order form changes, the report tests fail too, although the report did not change. Page Object and App Actions answer different halves of this problem. This lesson covers what each solves, how they combine and when one of them is unnecessary.

How it works and why. Page Object gathers a page's selectors and actions into a class, so a test reads as a scenario and a locator changes in one place. It solves the maintenance problem: what to do when the interface changed. App Actions control the application's state directly instead of clicking: through the API (cy.request), through cy.task into the database or through functions the app exposes on window. They solve the speed and fragility of setup problem: state need not be built through a UI that is not the subject of the test. The Cypress docs advise against using the UI for login and data setup, which is exactly the App Actions idea.

What each approach solves

Page Object

Actions the test verifies

A page's selectors and methods in one class. An interface change is fixed in one place.

App Actions

State setup

Data and session are created through the API or an app function. Fast and independent of forms.

Figure 1. They are not rivals: one owns the page, the other owns the state.

Example: from a long scenario to two layers. Before: setup goes through the UI although the test only checks the chart.

it('the chart shows 30 days', () => {
  cy.visit('/orders/new');
  cy.get('[data-cy=product]').select('Book');
  cy.get('[data-cy=qty]').type('2');
  cy.get('[data-cy=save]').click();
  // ... four more orders
  cy.visit('/statistics');
  cy.get('[data-cy=period-select]').select('30d');
  cy.get('[data-cy=stats-chart]').should('be.visible');
});

After: a command creates the orders through the API and a Page Object handles the page. This assumes POST /api/orders exists and accepts the session from cy.login.

// cypress/support/pages/statistics.page.ts
export class StatisticsPage {
  visit() {
    cy.visit('/statistics');
    return this;
  }
  selectPeriod(value: string) {
    cy.get('[data-cy=period-select]').select(value);
    return this;
  }
  chart() {
    return cy.get('[data-cy=stats-chart]');
  }
}

// the test
const stats = new StatisticsPage();
beforeEach(() => {
  cy.login('anna@example.com', 'secret');
  cy.request('POST', '/api/orders', { product: 'Book', qty: 2 });
});
it('the chart shows 30 days', () => {
  stats.visit().selectPeriod('30d').chart().should('be.visible');
});

Why this way. The test stays about one thing: the chart. A change to the order form no longer touches it, because the form takes no part in the scenario, and a change to the period selector is fixed in selectPeriod. Methods return this or a cy chain, never an element in a variable: Cypress commands are asynchronous and a saved "element" goes stale. Assertions are better left in the test: a Page Object describes what can be done, the test says what must be true.

Limits and alternatives. App Actions need a foothold in the application: an API for creating data or a function exposed only in test mode (for example when window.Cypress exists). If there is no such path, you are left with the UI or database queries through cy.task. A Page Object is not mandatory for a small suite: when a page has two selectors, a class adds a layer for nothing. There is a lighter form too: a module of functions and custom commands. In Playwright a Page Object with async methods is usually passed in through fixtures, and App Actions are done through page.evaluate() or the API.

Common mistakes.

  • Preparing state through the UI when the test checks something else: slow, and it breaks when someone else’s form changes.
  • Putting assertions and branching logic into a Page Object: the test stops showing what is verified.
  • Exposing app functions on window in production rather than for tests only: that is a backdoor for everyone.
  • A Page Object for every detail: more files than tests.

Check yourself

A test checks the filter in the orders list. Which part of the setup belongs in an App Action and which stays in the UI?

Answer

Creating the orders and logging in go to an App Action (API or command), since they are not the subject of the test. Working with the filter itself stays in the UI through a Page Object, because that is what the test checks.

Why does a Page Object return this or a cy chain instead of an element?

Answer

Cypress commands are queued and run later. An element saved in a variable can go stale, while a chain performs the lookup again every time, with retries.

In an interview. Junior: I use a Page Object so locators sit in one place and a test reads as a scenario. For state setup the API fits better than forms. Middle/Senior: A Page Object owns UI maintenance, App Actions own the speed and stability of setup. I set state through the API and go through the UI only where it is the subject of the test. I keep assertions in the test and expose window functions in test mode only.

What are fixtures in Cypress? Are they the same as in Playwright?

In Cypress a fixture is a data file, while in Playwright it is a function with setup and teardown: the word is the same, the meaning differs. The cy.fixture() command reads a file from cypress/fixtures and has no lifecycle. Playwright prepares a resource before await use() and cleans up after it. In Cypress hooks, custom commands and cy.session play that role, and cleanup is better done before the test.

Cypress · Patterns and data

A job post asks for "fixtures experience". Which kind: Cypress or Playwright?

A Playwright candidate talks about fixtures: scopes, dependencies, teardown. A Cypress interviewer asked about a JSON file with a test user. Both used the same word and did not understand each other. This lesson separates the two meanings, shows how each works and what plays the role of Playwright fixtures in Cypress.

How it works and why. In Cypress a fixture is a data file in the cypress/fixtures folder (the path is set by the fixturesFolder option). cy.fixture() reads it, and the .json extension can be omitted. A fixture has no lifecycle: it prepares and cleans up nothing. In Playwright a fixture is a function with setup and teardown: code before await use(value) prepares a resource, code after it cleans up, and the test receives the value as a parameter. So one word means different things: "data" versus "a dependency with a lifecycle".

One word, two things

Cypress

A data file

cypress/fixtures/*.json. Read by cy.fixture() or used as a response in intercept. Cleans up nothing.

Playwright

A dependency with a lifecycle

test.extend(): setup, await use(), teardown. Test and worker scopes, dependencies between fixtures.

Figure 1. The name matches, the purpose differs.

Example: data from a file. The file cypress/fixtures/users/admin.json contains { "email": "admin@example.com" }. The test uses it two ways: in a form field and as a network response.

cy.fixture('users/admin').then((admin) => {
  cy.get('[data-cy=email]').type(admin.email);
});

// an empty response instead of a call to the server
cy.intercept('GET', '/api/stats', { fixture: 'stats-empty.json' });
cy.visit('/statistics');
cy.get('[data-cy=empty-state]').should('be.visible');

// alias: this.admin works in function(), not in an arrow
beforeEach(() => cy.fixture('users/admin').as('admin'));
it('uses the alias', function () {
  cy.get('[data-cy=email]').type(this.admin.email);
});

Why this way. A fixture with cy.intercept gives a predictable response: the "empty report" state is reproduced without preparing the database. Cypress caches a fixture’s contents, but every cy.fixture call yields a copy, so mutating the returned object does not affect later calls. Editing the file itself during the run is not picked up, though: the cached contents apply. An alternative: import admin from '../fixtures/users/admin.json' with resolveJsonModule in tsconfig, where the data is typed instead of loaded by a command.

What replaces Playwright fixtures in Cypress. Closer analogues: beforeEach/before for setup, custom commands for repeated actions, cy.session for a logged-in state and .as() aliases for passing values. There is no worker scope, dependencies between "fixtures" are not declared, and in Cypress cleanup is better done before a test: an after hook does not run if the run is interrupted.

Common mistakes.

  • Calling cy.fixture "like in Playwright": in an interview this shows mixed-up terms.
  • Putting real passwords or tokens in the JSON: the file lands in the repository.
  • Using this.admin in an arrow function: this is empty, you need function () {}.
  • Counting on after to remove data: after an interrupted run it stays.

Check yourself

A test with cy.get(...).type(this.admin.email) fails with "Cannot read properties of undefined". The alias is created in beforeEach. What is wrong?

Answer

Most likely the test is an arrow function: it has no this of its own, so the alias is unavailable. Use it(..., function () { ... }) or read the value with cy.get('@admin').

Which part of a Playwright fixture (setup, value, teardown) does cy.fixture not give at all?

Answer

Setup and teardown: cy.fixture only returns data from a file. Cypress does setup and cleanup with hooks, commands and cy.session.

In an interview. Junior: In Cypress a fixture is a file of test data that I load with cy.fixture or use as an intercept response. In Playwright it is a dependency injection mechanism. Middle/Senior: When asked about fixtures I first clarify the tool. In Cypress they are data with no lifecycle, so I do setup and teardown with hooks, commands and cy.session, and put cleanup before the test. I treat file data as read-only.

How do you configure different environments and environment variables?

Cypress environments are set with variables: secrets are read with cy.env(), public values with Cypress.expose(); Cypress.env() was removed in 16. Secrets come from the env block of the config, a cypress.env.json file outside git, OS variables with the CYPRESS_ prefix or the --env flag, public values from the expose key or --expose. The environment is chosen with a flag, and baseUrl is set in setupNodeEvents.

Cypress · Patterns and data

The test is green on dev, and on staging it logs in with someone else’s password. Where does Cypress take the values from?

The same suite runs locally, on dev, on staging and in CI. The app address, login and password differ each time, and the password may be neither committed nor printed in logs. Cypress has several sources of values for this, and when there are several, one of them wins. This lesson covers how the sources work, how secret and public values differ and how to switch environments without editing tests.

How it works and why. Values are usually set in four places (the fifth, setupNodeEvents, appears in the example below): the env block in cypress.config.ts, the cypress.env.json file, OS environment variables with the CYPRESS_ prefix and the --env flag. When a name matches, the later source in the list wins: the flag overrides the OS variable, the variable overrides the file, the file overrides the config. This is convenient: the config holds safe defaults and CI overrides them with its own.

Reading a value in a test now takes two paths. Secrets are taken asynchronously with cy.env(['NAME']): the command yields an object with the requested keys, so the value does not sit in the general config object. Public settings, such as an API address, are read synchronously with Cypress.expose('NAME'). The old Cypress.env() was removed in Cypress 16, so code from old examples on the web needs rewriting.

Who wins when a name matches

1. env in cypress.config.tssafe defaults2. cypress.env.jsonlocal secrets, not in git3. CYPRESS_NAME in the OShow CI passes secrets4. --env name=valueoverrides everything else
Figure 1. The lower in the list, the stronger the source. Look there when a value is "wrong".

Example: from hard-coded values to environments. Before: the address and password right in the test, with a copy for staging in another file.

cy.visit('https://dev.example.com/login');
cy.get('[data-cy=email]').type('anna@example.com');
cy.get('[data-cy=password]').type('P@ssw0rd-from-dev');

After: the config picks baseUrl by environment name and the test takes secrets from cy.env. If the environment name is wrong, it is better to stop at once than to silently get undefined.

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

const urls: Record<string, string> = {
  dev: 'https://dev.example.com',
  staging: 'https://staging.example.com',
};

export default defineConfig({
  expose: { apiUrl: '/api' },
  e2e: {
    setupNodeEvents(on, config) {
      const name = String(config.env.envName ?? 'dev');
      if (!urls[name]) throw new Error('Unknown environment: ' + name);
      config.baseUrl = urls[name];
      return config;
    },
  },
});

// the test
cy.visit('/login');
cy.env(['USER_EMAIL', 'USER_PASSWORD']).then(({ USER_EMAIL, USER_PASSWORD }) => {
  cy.request('POST', Cypress.expose('apiUrl') + '/auth/login', {
    email: USER_EMAIL,
    password: USER_PASSWORD,
  });
});
# CI: the secret comes from the pipeline store
CYPRESS_USER_EMAIL=ci-bot@example.com \
CYPRESS_USER_PASSWORD="$STAGING_PASSWORD" \
npx cypress run --env envName=staging

Why this way. The test does not know where it runs: the outside world defines the environment. The secret is written nowhere in the repository: locally it sits in cypress.env.json (this file goes into .gitignore), in CI in a variable from the secret store. Besides --env, you can switch environments with a separate config: --config-file cypress.staging.config.ts, or override baseUrl with the CYPRESS_BASE_URL variable.

Limits and alternatives. Hiding a secret in Cypress does not replace discipline: a value in --env is visible in the process list, and cy.log() or type() without { log: false } prints it to the command log and the video. Prefer dedicated test accounts with limited rights over real ones. In Playwright variables are plain process.env, usually with dotenv, and environments are set through use.baseURL or separate projects.

Common mistakes.

  • Committing cypress.env.json with a password: the secret stays in git history even after the file is deleted.
  • Using Cypress.env() from old examples: it is gone in Cypress 16.
  • A typo in a CI variable name (CYPRESS_USER_PASWORD): the value is empty and the test fails at login, not at configuration.
  • Typing a password with type() without { log: false }.

Check yourself

The config has env.baseHost = "dev", cypress.env.json has the same field as "staging", and the run uses --env baseHost=prod. Which value does the test see?

Answer

"prod": the --env flag is stronger than the OS variable, the file and the config.

How do cy.env() and Cypress.expose() differ in purpose and in the way of reading?

Answer

cy.env is for secrets: an asynchronous command that yields only the requested keys. Cypress.expose is for public settings: a synchronous call, values visible to tests and the app.

In an interview. Junior: I read secrets with cy.env and public settings with Cypress.expose. Locally they sit in cypress.env.json outside git, and in CI they are passed as CYPRESS_ variables from the pipeline secrets. Middle/Senior: I know the priority order: config, file, OS variable, the --env flag. I pick the environment with a flag and set baseUrl in setupNodeEvents, failing at once on an unknown name. I keep the password out of logs, and in Playwright this is process.env and projects.

What are cy.task and setupNodeEvents?

A test runs in the browser with no access to a database or files, so cy.task provides the bridge into Node. The function is registered in setupNodeEvents through on('task', {...}) and the test calls it by name. The argument is serialised, so one object is passed, and the task must return a value, a Promise or null. Dangerous tasks such as a reset are tied to the test database.

Cypress · Patterns and data

The test clicked "Pay". How do you check that the order in the database really became paid?

The interface showed "Paid", but QA wants to know what is written in the database, and also to reset data before the test. Writing import { Client } from 'pg' straight in a spec will not work: test code runs in the browser, which has no sockets to a database and no file system. cy.task and setupNodeEvents provide a bridge into Node. This lesson covers how the bridge works, what you can pass and return, and its limits.

How it works and why. Cypress consists of two processes. The spec runs inside the browser next to the application. Separately runs Cypress's Node process, which reads cypress.config.ts and calls setupNodeEvents. In it, on('task', { ... }) registers named functions. The call cy.task('name', arg) serialises the argument, sends it to Node, runs the function and returns the result into the test. The isolation is deliberate: test code gets no access to the machine, and everything that needs Node goes through explicitly named tasks.

The bridge between the test and Node

Browsercy.task('db:query')Nodeon('task', {…})argresultJSON data only: no functions or DOM elements.
Figure 1. The argument and result travel as serialised data, so you can pass numbers, strings, objects and arrays.

Example: checking state in the database. Before: the test only looks at the text "Paid" in the interface. If the UI updated optimistically and the database write did not happen, the test passes. This assumes a PostgreSQL database with an orders table and a row id = 1042.

// cypress.config.ts
import { defineConfig } from 'cypress';
import { Pool } from 'pg';

const pool = new Pool({ connectionString: process.env.DB_URL });

export default defineConfig({
  e2e: {
    setupNodeEvents(on) {
      on('task', {
        async 'db:orderStatus'(id: number) {
          const res = await pool.query('SELECT status FROM orders WHERE id = $1', [id]);
          return res.rows[0]?.status ?? null;
        },
        async 'db:reset'() {
          await pool.query('TRUNCATE orders RESTART IDENTITY CASCADE');
          return null;
        },
      });
    },
  },
});

// the test
before(() => cy.task('db:reset'));
it('payment stores the paid status', () => {
  cy.visit('/orders/1042');
  cy.get('[data-cy=pay]').click();
  cy.get('[data-cy=status]').should('have.text', 'Paid');
  cy.task('db:orderStatus', 1042).should('eq', 'paid');
});

Why this way. A task receives one argument (pass an object for several values) and must return a value, a Promise or null: returning undefined makes Cypress complain that the task returned nothing. SQL with a $1 parameter is safer than gluing a string from the test. The pool is created once per run, not per call. In the sample db:reset is a TRUNCATE: a dangerous command, so DB_URL must point only at a test database. The test checks the final state twice: what the user sees and what is stored.

Limits and alternatives. A task has a time limit: the taskTimeout option, 60 seconds by default, and a single call can pass { timeout } as the third argument. An error thrown in a task fails the command and the test. Changing config at run time is the job of setupNodeEvents: through config and returning config; it is also where you subscribe to events such as before:browser:launch and after:spec. Lighter alternatives: cy.readFile and cy.writeFile work with files, cy.request calls an HTTP API. The cy.exec command was removed in Cypress 16, so shell commands now run inside a task through child_process. A task is needed where these do not reach, for instance a database. Playwright has no such layer: the test already runs in Node and imports the database client straight into the test or a fixture.

Common mistakes.

  • A task with no return: Cypress requires a value or null, otherwise the command fails.
  • Importing pg or fs in a spec instead of a task: these modules are not there in the browser.
  • Passing several values to a task as separate arguments: only one reaches it, you need one object.
  • Running db:reset against a shared database: other people’s data disappears.

Check yourself

The task log(message) runs console.log(message) and returns nothing. What happens on cy.task('log', 'hi')?

Answer

The command fails with an error that the task returned no value. Add return null.

Why can cy.task('db:orderStatus', 1042) be chained straight into .should('eq', 'paid')?

Answer

Because cy.task is an ordinary command: it yields the task result as the subject for the following steps. But should does not rerun the task itself, it only asserts the value received, so if the database write has not landed yet, you need retries another way.

In an interview. Junior: A test runs in the browser, so I reach the database or files through cy.task: I register a task in setupNodeEvents, it runs in Node and returns the result. A task must return something, at least null. Middle/Senior: I understand the two Cypress processes and that only serialised data crosses the bridge. I keep tasks narrow, with parameterised SQL and a pool, and tie dangerous ones like reset to the test database. For files and HTTP I use readFile and request, and I run shell commands through a task because cy.exec was removed in Cypress 16; Playwright needs no bridge.

Fixtures in Cypress vs Playwright

A Playwright fixture is reproduced in Cypress with hooks, aliases and cy.session, but only partly. Setup goes in beforeEach or a custom command, the value is passed through an .as() alias, and cy.session caches the login. Teardown is not guaranteed, because an after hook may not run if the run is interrupted, so state is reset at the start of the test. There is no worker scope.

Cypress · Patterns and data

In Playwright a test receives an order as a parameter and it cleans itself up. How do you do that in Cypress?

A team moves from Playwright to Cypress (or back) and ports a test that needs an order. In Playwright it arrives as the order parameter and is removed after the test by itself. Cypress has no such parameter. This article does not repeat what a fixture file is. It answers a practical question: how to reproduce the behaviour of Playwright fixtures with Cypress tools and where it cannot be reproduced.

How it works and why. A Playwright fixture has three parts: setup, a value, teardown. The runner calls it before a test that asked for it and cleans up after it, even when the test failed. Cypress splits this role into separate mechanisms: setup in hooks and commands, passing the value through an alias, and cleanup is left to you. The difference is fundamental: Playwright guarantees teardown, while Cypress does not guarantee that an after hook runs at all (for example when the run is interrupted).

PlaywrightCypress
The order parameterAlias .as('order') and this.order or cy.get('@order')
Setup before use()beforeEach or a custom command
Teardown after use()Cleanup before a test; after has no guarantee
The worker scopeNone: before applies within a spec, cy.session caches login
auto: trueA global beforeEach in support/e2e.ts
JSON data: a plain importcy.fixture() or a JSON import

Cleanup: who is responsible for it

Playwright

Teardown is guaranteed

Code after await use(order) runs even when the test failed. The runner does the cleanup.

Cypress

Cleanup before the test

Every test starts from a known state. An after hook may not run, so nothing relies on it.

Figure 1. Different guarantees push toward different designs: in Cypress you reset state at the start.

Example: the same order with two tools. Assumptions: the app has POST /api/orders, DELETE /api/orders/:id and a test-only reset endpoint POST /api/test/reset. Playwright:

import { test as base, expect } from '@playwright/test';

export const test = base.extend<{ order: { id: number } }>({
  order: async ({ request }, use) => {
    const res = await request.post('/api/orders', { data: { product: 'Book' } });
    const order = await res.json();
    await use(order);
    await request.delete('/api/orders/' + order.id);
  },
});

test('shows the order', async ({ page, order }) => {
  await page.goto('/orders/' + order.id);
  await expect(page.getByTestId('status')).toHaveText('new');
});

Cypress:

beforeEach(() => {
  cy.request('POST', '/api/test/reset');   // cleanup at the start
  cy.login('anna@example.com', 'secret');
  cy.request('POST', '/api/orders', { product: 'Book' })
    .its('body')
    .as('order');
});

it('shows the order', function () {
  cy.visit('/orders/' + this.order.id);
  cy.get('[data-cy=status]').should('have.text', 'new');
});

Why this way. Cypress clears browser cookies and storage between tests (test isolation is on by default), but server data stays. So a reset at the start is more reliable than deletion at the end: it works even after an abruptly interrupted run. The function () {} form is needed for this.order to work. With an alias created in beforeEach, the test receives the value as a Playwright test does with a parameter, although the alias is not type-checked.

Limits and alternatives. Not reproduced: the worker scope, automatic ordering of dependencies between fixtures, a typed parameter, guaranteed teardown. For reuse, custom commands and cy.session help, and for types you can wrap the fetching in a command with a declared Chainable. This is not "worse", it is a different model: Cypress keeps a test linear and relies on resetting state rather than on a hierarchy of dependencies. For data served as a network response, a fixture stays a file: cy.fixture or { fixture } in cy.intercept.

Common mistakes.

  • Cleaning data only in after/afterEach: after a broken run the next one starts with dirty state.
  • Looking for a "fixture parameter" in Cypress and writing your own wrapper: an alias is simpler.
  • Relying on spec order, because before is not shared between files.
  • Calling a JSON file "a fixture as in Playwright" in an interview.

Check yourself

A Cypress test creates an order in beforeEach and deletes it in afterEach. The run was interrupted mid-test. What happens on the next run?

Answer

The order stays in the system because afterEach did not run. If tests assume an empty state they may fail. Resetting data at the start of each test is more reliable.

Why is the Cypress test in the example written as function () {} and not an arrow?

Answer

The alias is available as this.order, and an arrow function has no this of its own. The alternative: an arrow and cy.get('@order').

In an interview. Junior: In Cypress fixtures are data files, and in Playwright a dependency injection mechanism with scopes. The Cypress analogue of the latter is hooks, custom commands and cy.session. Middle/Senior: In Cypress I reproduce setup and the value with hooks and aliases, but teardown is not guaranteed, so I reset state at the start of a test. There is no worker scope, and I cache login with cy.session. So before answering I clarify which tool is meant.

Page Object vs App Actions

Page Object and App Actions are not alternatives: the first controls how a test interacts with the interface, the second the state it starts from. The choice depends on what the test checks: steps under test go through a Page Object, and the starting state is prepared through App Actions. One test stays end to end through the form, so a bug in it does not pass unnoticed.

Cypress · Patterns and data

A test adds a task through a form although it only checks a counter. What is the right design?

Page Object and App Actions are often presented as "either-or", and arguments follow in code review. In fact they are two different knobs: one controls how a test interacts with the interface, the other how it prepares state. The lesson compares them by cost, risk and limits rather than repeating what they are; for the plain definitions see the lesson "Page Object or App Actions: which do you choose?".

How it works and why. A Page Object works at the interface level: a class wraps selectors and actions, and the test calls methods. It costs a layer: one more file to maintain and the temptation to hide logic in it. App Actions work beneath the interface: the test calls the API, cy.task or an application function. They are cheap in run time but more tightly coupled to the implementation: a change in the API or an internal function breaks the setup. So the choice becomes "what does this test check": if the interface, use a Page Object for its steps and create everything else with App Actions.

Two layers under a test

Testthe scenario and assertionsPage ObjectUI steps under testApp Actionsstate: API, cy.task, window
Figure 1. Assertions stay in the test, UI steps in the Page Object, setup beneath.

Example: an App Action through window. Assumptions: a React app with a store, and the team agreed to expose actions in test mode only. In the application code:

// src/main.tsx
if ((window as any).Cypress) {
  (window as any).appActions = {
    addTask: (title: string) => store.dispatch(addTask(title)),
  };
}

In the test: the counter is checked at once, with no form. A Page Object is needed only where the UI is the subject of the check.

it('the counter shows 2', () => {
  cy.visit('/tasks');
  cy.window().its('appActions').invoke('addTask', 'Buy milk');
  cy.window().its('appActions').invoke('addTask', 'Call bank');
  cy.get('[data-cy=counter]').should('have.text', '2');
});

// and a scenario where the UI is the very subject
class TasksPage {
  row(title: string) { return cy.contains('[data-cy=task]', title); }
  complete(title: string) {
    this.row(title).find('[data-cy=done]').click();
    return this;
  }
}
it('the checkbox strikes the task out', () => {
  cy.visit('/tasks');
  cy.window().its('appActions').invoke('addTask', 'Buy milk');
  new TasksPage().complete('Buy milk').row('Buy milk').should('have.class', 'done');
});

Why this way. The first test does not depend on how the add form looks. The second uses the App Action for the start only and does the real check through the Page Object. its() retries until the application has registered the actions. The drawback is clear: the test knows an internal function, so renaming it breaks both tests. That is why such actions are kept in a narrow, named object rather than exposing the whole store.

SituationChoice
UI behaviour is checkedPage Object
Initial state is needed and the UI is not the subjectApp Actions: API or cy.task
No API and no hook in the applicationUI, but inside a custom command
A small suite, one pageNo layer: direct cy calls

Limits and alternatives. Actions exposed on window work only in browser e2e: they must not exist in production, and a window.Cypress check in the app means it knows about tests. Alternatives: a dedicated test API, cy.task with direct database access, and for isolated components Cypress component tests. In Playwright, Page Object pages are usually passed in through fixtures, and App Actions are done through page.evaluate() or the API.

Common mistakes.

  • Saying "Page Object is obsolete": it is fine for UI steps, just not for state setup.
  • Exposing the whole store on window without tying it to test mode: an open backdoor.
  • Putting assertions in a Page Object: one method both acts and checks, and the test does not show the expectation.
  • Using App Actions for something that must be tested through the UI: the test misses a broken form.

Check yourself

The add-task form has a bug: the button sends nothing. The test with the addTask App Action passes. Why and what do you do?

Answer

The App Action bypasses the form, so the bug is invisible. You need a separate test that goes through the UI (a Page Object), while App Actions stay for tests where the form is not the subject.

Why are the actions on window registered under a window.Cypress condition?

Answer

So they are not available to ordinary users: a test hook must not be reachable in production. It is not a security measure, only hygiene, so the actions are kept narrow and safe.

In an interview. Junior: A Page Object gathers a page’s selectors and actions in one class. App Actions prepare state directly, without the UI. I combine both: the steps the test verifies go through a Page Object. Middle/Senior: They are different knobs: a Page Object controls UI interaction, App Actions control state. I choose by what the test checks, keep window actions narrow and test-mode only, and leave one test end to end through the form so a bug there does not pass unnoticed.