| | |

Cypress 28 ๐ŸŒฒ Migration from Playwright โ€” Selector differences, async model, and trade-offs

โฑ๏ธ Estimated read: 25 min | |

Almost every migration article on the internet runs in one direction: Cypress to Playwright. This chapter runs in the other one. A team that has decided to move to Cypress โ€” usually for the live runner, for a reporting pipeline already built around Cypress Cloud, or because the whole team writes JavaScript and the component testing story matters โ€” finds that the advice available online is not merely unhelpful but actively misleading, because every pitfall it documents is the mirror image of the one they will hit.

The two tools disagree at the most fundamental level. Playwright is ordinary asynchronous JavaScript: page.getByRole() returns a plain object, await locator.click() returns a promise, and every line executes in the order it appears. Cypress is a command queue: cy.get() enqueues a command, returns a chainable placeholder, and the queue runs after the test function has already returned. Code written in the Playwright shape โ€” an async test body, an await in front of every call โ€” does not fail loudly in Cypress. It fails in a way that can look like the test passing.

This chapter covers that rewrite in the order it has to happen. The selector section maps the Playwright locator vocabulary onto cy.get, cy.contains, and the @testing-library/cypress role commands, and explains what the data-cy convention actually buys. The async section is the important one: it covers why await must be deleted rather than added, how cy.then() replaces a return value, why aliases replace local variables, and what the queue does with a promise it was handed. The third section covers retries, the should()-versus-then() distinction, and the testIsolation default that changes how a file of tests is written. The fourth covers the supporting machinery โ€” cy.intercept, cy.fixture, cy.task, cy.request, cy.session, cy.clock โ€” and the fifth states the trade-offs plainly rather than pretending the move is free.

Key point: Playwright and Cypress disagree about when code runs. Playwright executes each line as it is reached, so a value is available on the next line; Cypress enqueues a description of the work and executes it after the test function returns, so a value is only available inside cy.then(). Delete every await, replace every local variable that held a page value with an alias, and the rest of the migration becomes mechanical.


Why the migration matters

The direction of travel is unusual. A Playwright-to-Cypress move is almost never a technical decision made on a feature comparison, because on a feature comparison Playwright wins most of the columns. It is an organisational decision: one team, one language, one runner in the office, one reporting contract with the quality team. That makes the migration a people problem wearing a technical costume, and the technical part still has to be done correctly or the organisational goal is not met.

The available advice is inverted. Every Cypress-to-Playwright guide lists the same traps โ€” forget await, read a value then assert on it, port the iframe workaround. Reversing the arrow reverses which of those are traps. In a Playwright-to-Cypress move, the await is the bug, the read-then-assert pattern is the correct one, and the iframe workaround is something you now have to acquire rather than remove.

The interactive runner is the argument that wins. Cypress’s cypress open holds the application in a real browser, snapshots the DOM before and after every command, and lets you hover a line and see the page as it was at that moment. Playwright produces a trace after the run; Cypress produces the moment during it. For a team whose debugging time is spent on “what did the page look like when this failed”, the runner is worth more than the parallelization Playwright gives away for free.

The await problem appears in reverse and it is silent. In Playwright, a missing await is also silent โ€” the action never fires โ€” which is why the ESLint rule exists. In Cypress the same bug looks different: the await cy.get(...) returns a chainable, the chainable is awaited and resolves immediately, and the command it described runs later anyway on the queue. Some tests keep working; some interleave wrongly; none of them error. Deleting the await is not a style preference, it is the precondition for predictable ordering.

The boundaries you inherit. Cypress runs the test code inside the browser frame, alongside the application. That is what makes the runner possible and it is also what imposes the boundaries: one origin per test without cy.origin(), one tab, no filesystem access from the test body without cy.task(). A Playwright codebase that opens popups, walks two domains in one test, and reads a JSON file from disk has three migrations to do, not one.

The trade-off. The move is not free and the account should be stated up front. Playwright gives free sharding via --shard, a first-class request fixture, a Node-side test body that can touch anything, and out-of-the-box WebKit. Cypress gives the runner, a queue that removes a whole class of race condition by construction, a single settled retry primitive in .should(), and Cypress Cloud’s parallelization as a paid product. A team should move when the runner and the reporting contract are worth more than the boundaries and the licence, and should say so out loud so nobody expects the lost capabilities to reappear.


a. The selector model โ€” locators to cy.get

Playwright’s default selector is a role, resolved against the accessibility tree. Cypress’s default is a CSS string resolved with jQuery, and its convention is a dedicated attribute โ€” data-cy โ€” that exists only for the tests and never for styling.

// cypress/e2e/save.cy.ts
it('saves the form', () => {
  cy.visit('/form');

  // Playwright: await page.getByTestId('email').fill('a@b.c')
  cy.get('[data-cy=email]').type('a@b.c');

  // Playwright: await page.getByRole('button', { name: 'Save' }).click()
  cy.get('[data-cy=save]').click();

  // Playwright: await expect(page.getByText('Order confirmed')).toBeVisible()
  cy.contains('Order confirmed').should('be.visible');
});

The role-based selectors do not disappear, they move into a plugin. @testing-library/cypress adds findByRole, findByLabelText, findByPlaceholderText, and findByText as commands, giving Cypress the same accessibility-tree resolution Playwright has built in.

// cypress/support/e2e.ts โ€” register the role commands once
import '@testing-library/cypress/add-commands';

// configure the test id attribute the plugin resolves
import { configure } from '@testing-library/cypress';
configure({ testIdAttribute: 'data-cy' });
// cypress/e2e/save.cy.ts โ€” now the Playwright shapes have twins
cy.findByRole('button', { name: 'Save' }).click();
cy.findByLabelText('Email').type('a@b.c');
cy.findByTestId('cart-count').should('have.text', '3');

The data-cy convention is a convention, not a setting. Unlike Playwright’s use.testIdAttribute, there is no config key that rewrites what cy.get() matches โ€” cy.get('[data-cy=x]') is an attribute selector and works because the attribute exists. What Cypress does offer is the selector playground, a picker in the runner that suggests a selector for a clicked element, and its priority list is configurable so that data-cy is preferred over a generated class name.

// cypress/support/e2e.ts โ€” affects the picker's suggestion, not cy.get
Cypress.SelectorPlayground.defaults({
  selectorPriority: ['data-cy', 'data-testid', 'id', 'class', 'tag'],
});

The chaining vocabulary maps almost one to one, with one inversion: Playwright narrows forward with .filter(), and Cypress narrows backward with .parent() and .closest() or scopes with .within().

// Playwright: page.locator('.list li').nth(2)
cy.get('.list li').eq(2);

// Playwright: page.getByRole('row').filter({ hasText: 'Alice' })
cy.contains('tr', 'Alice');                      // the row containing Alice

// Playwright: page.locator('tr').filter(...).getByRole('button').click()
cy.contains('tr', 'Alice').find('[data-cy=edit]').click();

// Playwright: page.getByRole('dialog').getByRole('button', { name: 'OK' })
cy.get('[role=dialog]').within(() => {
  cy.contains('button', 'OK').click();           // scoped to the dialog
});

.within() is the construct Playwright does not have, and it is worth acquiring deliberately: everything inside the callback resolves against the subject, which is clearer than a long chain of .find() calls when the scope genuinely is a component.

The iframe is the one place where Cypress is strictly worse and the workaround has to be learned rather than removed. Playwright’s frameLocator scopes into a frame and re-resolves on each action; Cypress reaches into the frame’s document once, wraps the body, and carries it forward.

// Playwright: page.frameLocator('#checkout').getByRole('button', { name: 'Pay' })
cy.get('#checkout')
  .its('0.contentDocument.body')                 // reach into the frame
  .should('not.be.empty')                        // wait for it to load
  .then(cy.wrap)                                 // re-wrap as a subject
  .find('[data-cy=pay]')
  .click();

b. The async model โ€” promises to the command queue

This section is the whole migration. Everything else is vocabulary.

In Playwright, page.getByRole('button') performs no query; it builds a description. await locator.click() resolves the description, waits for actionability, clicks, and resolves the promise. The value the promise resolves to is available on the next line, in a local variable, right away.

In Cypress, cy.get('[data-cy=btn]') performs no query either โ€” it enqueues a command. The chainable it returns is a placeholder that records what to do. Nothing happens until the test function returns, at which point Mocha hands control to Cypress’s queue runner, which executes the queued commands in order.

// Playwright โ€” each line runs when it is reached
const btn = page.getByRole('button', { name: 'Save' });   // description
await btn.click();                                          // runs now
const text = await page.locator('h1').textContent();        // value now

// Cypress โ€” each line only enqueues
cy.get('[data-cy=save]').click();                           // enqueued
cy.get('h1').invoke('text').then((text) => {                // read in .then
  cy.wrap(text).should('eq', 'Welcome');                    // yields here
});

The consequence that catches everyone: a local variable assigned from a Cypress chain holds a placeholder, not a value. The const text in a Playwright test holds a string. The const el in a Cypress test holds a chainable, and using it later โ€” especially across commands โ€” reads nothing.

// WRONG โ€” `$el` is a chainable, not an element
const $el = cy.get('[data-cy=total]');
cy.wrap($el).should('have.text', '10.00');                  // โŒ

// RIGHT โ€” read inside .then(), where the subject is real
cy.get('[data-cy=total]').then(($el) => {
  expect($el.text().trim()).to.eq('10.00');                 // โœ…
});

// RIGHT โ€” or assert on the element with a retrying assertion
cy.get('[data-cy=total]').should('have.text', '10.00');     // โœ…

The replacement for a variable that needs to survive across commands is an alias. .as('name') stores the subject, cy.get('@name') retrieves it, and โ€” for network requests โ€” cy.wait('@name') waits for it, which is the one piece of Playwright’s waitForResponse that has a direct Cypress twin.

// Playwright: const resPromise = page.waitForResponse('**/api/cart')
//             await page.getByTestId('refresh').click()
//             await resPromise
cy.intercept('GET', '/api/cart').as('cart');                // name the route
cy.get('[data-cy=refresh]').click();
cy.wait('@cart');                                            // wait for it

And async must be removed from the test body. Cypress’s queue and native promises do not compose: an async test function returns a promise to Mocha immediately, Mocha considers the test finished, and the queued commands run against a test that is already over. The Cypress docs warn against it directly, and the symptom โ€” output that appears after the test is reported โ€” is exactly what the warning describes.

// WRONG โ€” the test function returns before the queue runs
it('loads the cart', async () => {
  await cy.visit('/cart');                                  // โŒ no-op await
  await cy.get('[data-cy=item]').should('have.length', 3);  // โŒ
});

// RIGHT โ€” synchronous body, the queue owns the order
it('loads the cart', () => {
  cy.visit('/cart');                                        // โœ…
  cy.get('[data-cy=item]').should('have.length', 3);        // โœ…
});

The one legitimate place to return a promise is inside a cy.then() callback, where Cypress does await what the callback returns. That is how a test interleaves a native async operation โ€” a fetch, a cy.task() that returns a promise โ€” with the queue.

cy.then(() => fetch('/api/health').then((r) => r.json())).then((health) => {
  expect(health.ok).to.be.true;                             // callback awaited
});

c. Retries, should() versus then(), and isolation

Playwright retries at two levels: every action re-resolves its locator and retries on detachment, and every expect(locator) polls until the timeout. Cypress has one retrying primitive, and it is attached to the assertion, not the action: a chain that ends in .should() re-runs the query and the assertion together until it passes or defaultCommandTimeout expires.

// the chain re-runs until the length is 3 or 4s elapse
cy.get('[data-cy=item]').should('have.length', 3);

// a .then() callback does not retry; it runs once with whatever it got
cy.get('[data-cy=item]').then(($items) => {
  expect($items).to.have.length(3);                         // โŒ no retry
});

That distinction is the direct translation of Playwright’s expect(locator) versus expect(value) rule, and it produces the same class of flake in the opposite direction. A Playwright port that turned every await expect(locator) into a .then() has removed the retry from every assertion in the file.

The timeouts differ and it matters which knob is which, because Cypress has no per-action timeout โ€” the command timeout covers the whole command including its actionability retries.

TimeoutPlaywrightCypress
Action0 (test timeout)defaultCommandTimeout 4 000 ms
Assertionexpect.timeout 5 000 msshares defaultCommandTimeout
Navigation30 000 mspageLoadTimeout 60 000 ms
Test30 000 msnone by default

Isolation is the structural difference that changes how files are written. Playwright creates a fresh browser context per test, so cookies, storage, and cache never leak. Cypress has kept the same browser and the same page across tests within a file for most of its life; since v12 the testIsolation: true default clears cookies and both storages and navigates to about:blank between tests, which recovers most of the Playwright guarantee without giving up the shared browser that makes the runner fast.

// cypress.config.ts โ€” the default, restated
export default defineConfig({
  e2e: {
    testIsolation: true,          // reset cookies + storage + page
    retries: { runMode: 2, openMode: 0 },
  },
});

What does not carry across from Playwright is the setup-project pattern. A Playwright suite logs in once in a setup project and reuses storageState; the Cypress equivalent is cy.session(), which caches the cookies and storage a setup block produced and restores them in milliseconds. The migration is a rename of the concept, not of the shape.

// Playwright: storageState written by a setup project
// Cypress: a cached session restored per test
beforeEach(() => {
  cy.session('user', () => {          // setup runs once per key
    cy.visit('/login');
    cy.get('[data-cy=email]').type('user@example.com');
    cy.get('[data-cy=password]').type('secret');
    cy.get('[data-cy=signin]').click();
    cy.url().should('include', '/dashboard');
  }, { cacheAcrossSpecs: true });     // reuse across spec files
});

d. The supporting machinery

Every Playwright helper the suite depended on has a Cypress counterpart, and the mapping is worth writing down once because the differences are in where the code runs, not in what it does.

Network stubbing. page.route becomes cy.intercept. The rewrite is mechanical, and the alias is what replaces waitForResponse.

// Playwright: await page.route('**/api/users', r => r.fulfill({ json: users }))
cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('users');

// Playwright: await page.route('**/api/order', r => r.fulfill({ status: 201 }))
cy.intercept('POST', '/api/order', { statusCode: 201, body: { id: 1 } });

// observe without stubbing
cy.intercept('GET', '/api/**', (req) => { req.continue(); }).as('any');

Fixtures. cy.fixture() reads from cypress/fixtures at run time and yields a promise-like via the queue; Playwright would have imported the JSON at build time. The Cypress form is worth preferring here because a fixture that can be switched per environment is not possible with a static import.

// Playwright: import users from '../fixtures/users.json'
cy.fixture('users.json').then((users) => {
  cy.intercept('GET', '/api/users', users);                 // read at runtime
});

Node-side work. This is the biggest conceptual gap. A Playwright test body is Node, so a database reset is an await. A Cypress test body runs in the browser, so the same reset has to be a cy.task registered in setupNodeEvents.

// cypress.config.ts โ€” the Node side
import { defineConfig } from 'cypress';
export default defineConfig({
  e2e: { baseUrl: 'http://localhost:3000' },
  setupNodeEvents(on) {
    on('task', {
      async resetDatabase() { await db.truncate(); return null; },  // must return
    });
  },
});

// the test side โ€” one command, same effect as an awaited function
cy.task('resetDatabase');

HTTP calls. request.get() becomes cy.request(). Cypress’s version does not need a fixture and does not share cookies with the page by default; cy.request errors on a non-2xx response unless failOnStatusCode: false is passed, which is the inverse of Playwright’s res.ok() check.

// Playwright: const res = await request.get('/api/orders')
cy.request('/api/orders').then((res) => {
  expect(res.status).to.eq(200);                            // 2xx implied
  expect(res.body).to.have.length(3);
});

Custom commands and fixtures. Playwright’s test.extend() becomes Cypress.Commands.add(), and the loss is the typed, per-test setup/teardown lifetime โ€” a command is a function on the cy object, so any teardown has to be registered separately.

// cypress/support/commands.ts โ€” the Playwright fixture, as a command
Cypress.Commands.add('login', (email: string, password: string) => {
  cy.session([email, password], () => {         // the setup half
    cy.visit('/login');
    cy.get('[data-cy=email]').type(email);
    cy.get('[data-cy=password]').type(password);
    cy.get('[data-cy=signin]').click();
  });
});

// declare the type so TypeScript accepts cy.login()
declare global {
  namespace Cypress {
    interface Chainable { login(email: string, password: string): Chainable<void> }
  }
}

The clock. page.clock.install() becomes cy.clock(), and the ordering constraint is the same: install before navigation, or the application captures the real timers.

// Playwright: await page.clock.install({ time: new Date('2025-01-01') })
cy.clock(Date.UTC(2025, 0, 1));                             // install first
cy.visit('/dashboard');
cy.tick(30_000);                                             // advance 30 s

e. The trade-offs, stated plainly

The move buys three things and costs four, and a team that does not name them will spend the first quarter discovering them one at a time.

// gained: the live runner
// $ npx cypress open
// hover any command โ†’ the DOM at that moment; click โ†’ pin the snapshot

// gained: no await discipline
// a missing await is impossible because there is nothing to await

// gained: guaranteed in-file order
// Mocha runs the tests in a file top to bottom, always

// lost: free sharding
// $ npx playwright test --shard=1/3      โ† Playwright, free
// $ npx cypress run --parallel --record  โ† Cypress, needs Cloud

// lost: multi-tab
// const [popup] = await Promise.all([page.waitForEvent('popup'), click()])

// lost: one test across two origins without a wrapper
cy.origin('https://shop.example.com', () => { /* runs in a callback */ });

// lost: test code in Python, Java, or .NET
// Playwright ships all three; Cypress is JavaScript and TypeScript only

The cy.origin() boundary is the one that hurts most in a real migration, because it is not a rename. The callback cannot share variables with the outer test, and any value has to be passed in through the options bag and out through an alias. A Playwright test that walked from a login domain to a checkout domain as one flat sequence becomes two scoped blocks with a handoff between them.

// Playwright โ€” one flat sequence, no boundary
await page.goto('https://auth.example.com/login');
await page.getByRole('button', { name: 'Sign in' }).click();
await page.goto('https://shop.example.com/checkout');       // just a goto

// Cypress โ€” the second origin is a scoped callback
cy.origin('https://shop.example.com', () => {
  cy.visit('/checkout');                                     // same tab
  cy.contains('button', 'Pay').click();
});

Complete Example Session

// ============================================
// PART 1: THE PLAYWRIGHT TEST, AS WRITTEN
// ============================================
// tests/checkout.spec.ts
// test('pays with a saved card', async ({ page }) => {
//   await page.route('**/api/pay', r => r.fulfill({ json: { ok: true } }));
//   const pay = page.waitForResponse('**/api/pay');
//   await page.goto('/cart');
//   await page.getByTestId('pay').click();
//   await pay;
//   await expect(page.getByText('Order confirmed')).toBeVisible();
// });

// ============================================
// PART 2: THE CYPRESS CONFIG
// ============================================
// cypress.config.ts
import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    baseURL: 'http://localhost:3000',       // replaces Playwright's baseURL
    testIsolation: true,                    // cookies + storage reset per test
    retries: { runMode: 2, openMode: 0 },   // CI retries, local honesty
  },
});

// ============================================
// PART 3: THE SUPPORT FILE
// ============================================
// cypress/support/e2e.ts
import '@testing-library/cypress/add-commands';   // findByRole, findByLabelText
import './commands';                              // custom commands

// ============================================
// PART 4: THE SELECTOR REWRITE
// ============================================
// cypress/e2e/checkout.cy.ts
it('pays with a saved card', () => {
  // Playwright's getByTestId('pay') โ†’ the data-cy attribute convention
  cy.visit('/cart');                              // no await, ever

  // ============================================
  // PART 5: THE NETWORK STUB
  // ============================================
  cy.intercept('POST', '/api/pay', { body: { ok: true } }).as('pay');
  cy.get('[data-cy=pay]').click();

  // ============================================
  // PART 6: THE ALIAS WAIT
  // ============================================
  cy.wait('@pay').its('response.statusCode').should('eq', 200);

  // ============================================
  // PART 7: THE RETRYING ASSERTION
  // ============================================
  // .should() re-runs the query until the text appears or 4 s elapse
  cy.contains('Order confirmed').should('be.visible');
});

// ============================================
// PART 8: THE CUSTOM COMMAND
// ============================================
// cypress/support/commands.ts
Cypress.Commands.add('login', (email: string) => {
  cy.session(email, () => {
    cy.visit('/login');
    cy.findByLabelText('Email').type(email);      // role-based via the plugin
    cy.get('[data-cy=password]').type('secret');
    cy.get('[data-cy=signin]').click();
    cy.url().should('include', '/dashboard');
  }, {
    cacheAcrossSpecs: true,                       // reuse across spec files
    validate() {
      cy.request({ url: '/api/me', failOnStatusCode: false })
        .its('status').should('eq', 200);         // force re-login on 401
    },
  });
});

// ============================================
// PART 9: THE SESSION IN USE
// ============================================
beforeEach(() => {
  cy.login('user@example.com');                   // ~40 ms after the first call
});

it('lists orders in order', () => {
  cy.visit('/orders');
  cy.get('[data-cy=order]').should('have.length.greaterThan', 0);
  cy.get('[data-cy=order]').first().should('contain', 'Newest');
});

// ============================================
// PART 10: THE CLOCK AND THE RUN
// ============================================
it('expires the session after two hours', () => {
  cy.clock(Date.UTC(2025, 0, 1));                 // install before navigation
  cy.visit('/dashboard');
  cy.tick(1000 * 60 * 120);                       // advance two hours
  cy.contains('Session expired').should('be.visible');
});

// $ npx cypress open                     โ†’ the live runner
// $ npx cypress run --browser chrome     โ†’ CI, headless

The ten parts covered the Playwright original, the Cypress config with baseURL and testIsolation, the support file and the role-command plugin, the selector rewrite, the cy.intercept stub, the alias wait that replaced waitForResponse, the retrying should(), the cy.session custom command with a validate callback, the session in use, and cy.clock with the CI run command.


Quick Reference

Selector mapping

PlaywrightCypress
page.getByRole('button', { name })cy.findByRole('button', { name }) (plugin)
page.getByTestId('x')cy.get('[data-cy=x]')
page.getByText('Save')cy.contains('Save')
page.getByLabel('Email')cy.findByLabelText('Email') (plugin)
page.locator('.row')cy.get('.row')
.nth(2).eq(2)
.filter({ hasText })cy.contains(sel, text)
frameLocator('#f').its('0.contentDocument.body').then(cy.wrap)
component scope.within(() => { ... })

Async model

PlaywrightCypress
async test bodysynchronous test body
await locator.click()cy.get(...).click()
const v = await โ€ฆcy.get(...).then(v => โ€ฆ)
local variable across steps.as('alias') + cy.get('@alias')
waitForResponsecy.intercept(...).as('x') + cy.wait('@x')

Supporting machinery

PlaywrightCypress
page.route(...)cy.intercept(...)
import data from './x.json'cy.fixture('x.json')
plain Node functioncy.task('name') + setupNodeEvents
request.get(...)cy.request(...)
storageState + setup projectcy.session() + cacheAcrossSpecs
test.extend({ ... })Cypress.Commands.add(...)
page.clock.install()cy.clock()

Timeouts and isolation

KnobPlaywrightCypress
Action timeout0 (test timeout)defaultCommandTimeout 4 s
Assertion timeoutexpect.timeout 5 sshares 4 s
Navigation30 spageLoadTimeout 60 s
Test30 snone
Isolation unitbrowser contexttestIsolation: true

Best Practices

โœ… Do This:

// Delete the async, keep the body synchronous
it('loads', () => { cy.visit('/cart'); });                       // โœ…

// Read a subject inside .then(), where it is real
cy.get('[data-cy=n]').then(($el) => expect($el.text()).to.eq('3')); // โœ…

// Or let .should() retry the whole chain
cy.get('[data-cy=n]').should('have.text', '3');                  // โœ…

// Use aliases for anything needed later
cy.intercept('GET', '/api/x').as('x'); cy.wait('@x');            // โœ…

// Register role commands once in the support file
import '@testing-library/cypress/add-commands';                  // โœ…

// Cache expensive setup with cy.session
cy.session(key, () => { /* login */ }, { cacheAcrossSpecs: true }); // โœ…

// Put every Node operation behind cy.task
cy.task('resetDatabase');                                        // โœ…

// Keep testIsolation on; fix slowness with sessions
testIsolation: true                                              // โœ…

โŒ Don’t Do This:

// Leave await in the test body
it('loads', async () => { await cy.visit('/cart'); });           // โŒ

// Store a chainable and use it as a value later
const $el = cy.get('[data-cy=n]'); expect($el.text()).to.eq('3'); // โŒ

// Replace every .should() with a .then()
cy.get('[data-cy=n]').then(($el) => expect($el).to.have.text('3')); // โŒ

// Reach for the filesystem from the test body
const fs = require('node:fs');                                    // โŒ

// Disable isolation to make logins fast
testIsolation: false                                              // โŒ

// Port an iframe locator as a bare cy.get
cy.get('#checkout').find('[data-cy=pay]').click();                // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Test “passes” but nothing ranawait left in the bodyMake the body synchronous
undefined from a stored chainableChainable used as a value.then() or .should()
Assertion never retries.should() ported to .then()Restore .should()
Selector finds nothingPlaywright’s data-testiddata-cy or the plugin
Role query missingPlugin not registeredimport '@testing-library/cypress/add-commands'
Iframe steps failframeLocator ported literallyits('0.contentDocument.body')
Cross-origin step errorsNo cy.origin() wrapperWrap the second domain
Database reset failsNode call in a browser bodycy.task()
Popup test impossibleCypress is single-tabTest the navigation instead

Real-World Examples

1. Remove the await

it('loads', () => { cy.visit('/cart'); });   // no async, no await

2. Read with .then()

cy.get('[data-cy=n]').then(($el) => expect($el.text()).to.eq('3'));

3. Assert with .should()

cy.get('[data-cy=n]').should('have.text', '3');

4. Alias a route

cy.intercept('GET', '/api/cart').as('cart');

5. Wait for it

cy.get('[data-cy=refresh]').click();
cy.wait('@cart');

6. Role command

cy.findByRole('button', { name: 'Save' }).click();

7. Scope with .within()

cy.get('[role=dialog]').within(() => cy.contains('button', 'OK').click());

8. Frame workaround

cy.get('#f').its('0.contentDocument.body').should('not.be.empty').then(cy.wrap);

9. Session cache

cy.session('user', () => { /* login */ }, { cacheAcrossSpecs: true });

10. Second origin

cy.origin('https://shop.example.com', () => cy.contains('button', 'Pay').click());

Visual

The async model

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  THE ASYNC MODEL                                       โ”‚
โ”‚                                                        โ”‚
โ”‚  PLAYWRIGHT โ€” promises, line by line                   โ”‚
โ”‚    const btn                          // description   โ”‚
โ”‚    await btn.click()                  // runs now      โ”‚
โ”‚    const text = await page.textContent // value now    โ”‚
โ”‚                                                        โ”‚
โ”‚  CYPRESS โ€” one queue, after the return                 โ”‚
โ”‚    cy.get('[data-cy=b]').click()      // enqueued      โ”‚
โ”‚    cy.get('h1').then(t => ...)        // enqueued      โ”‚
โ”‚                                                        โ”‚
โ”‚  the queue runs after the test function returns        โ”‚
โ”‚  โ†’ no await, no return value, read inside .then()      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The selector translation

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SELECTOR TRANSLATION                                  โ”‚
โ”‚                                                        โ”‚
โ”‚  Playwright                Cypress                     โ”‚
โ”‚  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€     โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€      โ”‚
โ”‚  getByRole('button')   โ†’   findByRole('button')        โ”‚
โ”‚  getByTestId('card')   โ†’   cy.get('[data-cy=card]')    โ”‚
โ”‚  getByText('Save')     โ†’   cy.contains('Save')         โ”‚
โ”‚  locator('.row').nth(2)โ†’   cy.get('.row').eq(2)        โ”‚
โ”‚  filter({ hasText })   โ†’   cy.contains(sel, text)      โ”‚
โ”‚  component scope       โ†’   .within(() => { ... })      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Retries and timeouts

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  RETRIES AND TIMEOUTS                                  โ”‚
โ”‚                                                        โ”‚
โ”‚                      PLAYWRIGHT     CYPRESS            โ”‚
โ”‚  action retry        every action   none               โ”‚
โ”‚  assertion retry     expect(loc)    .should()          โ”‚
โ”‚  command timeout     0 / test 30s   4s                 โ”‚
โ”‚  assertion timeout   5s             4s                 โ”‚
โ”‚  navigation timeout  30s            60s                โ”‚
โ”‚  isolation unit      context        testIsolation      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

What changes in the move

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  WHAT CHANGES IN THE MOVE                              โ”‚
โ”‚                                                        โ”‚
โ”‚  gained                                                โ”‚
โ”‚    time travel in a live runner                        โ”‚
โ”‚    no await discipline to remember                     โ”‚
โ”‚    guaranteed in-file test order                       โ”‚
โ”‚                                                        โ”‚
โ”‚  lost                                                  โ”‚
โ”‚    free sharding without Cypress Cloud                 โ”‚
โ”‚    multi-tab, and two origins without cy.origin()      โ”‚
โ”‚    Python, Java, and .NET test code                    โ”‚
โ”‚    per-action auto-retry                               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Test bodySynchronous โ€” no async, no await
Value from the pageRead inside .then()
Retrying assertion.should() โ€” not .then()
Cross-step value.as('alias') + cy.get('@alias')
Test id conventiondata-cy
Role selectors@testing-library/cypress plugin
Component scope.within(() => { ... })
Network stubcy.intercept(...).as('x')
Network waitcy.wait('@x')
Node-side workcy.task() + setupNodeEvents
Cached logincy.session() + cacheAcrossSpecs
Second origincy.origin()

Key takeaways:

  • Delete the await, do not add it. Playwright’s test body is a promise chain and Cypress’s is a synchronous enqueue. An async Cypress test returns to Mocha before its commands run, and the symptom is output that appears after the test has been reported as finished. This is the single change that must happen before anything else is migrated.
  • A chainable is a description, not a value. cy.get(...) returns a placeholder. Whatever a Playwright test stored in a local variable has to become an alias (.as('x')) or be read inside a .then() callback, because the value does not exist until the queue reaches that command.
  • .should() retries and .then() does not. This is the Cypress form of Playwright’s expect(locator) versus expect(value) rule, and a mechanical port that turns every await expect(locator) into a .then() has silently removed the retry from every assertion in the file.
  • data-cy is a convention, not a setting. Unlike Playwright’s testIdAttribute, no config key rewrites what cy.get() matches โ€” the attribute selector works because the attribute is there. The role-based selectors come from @testing-library/cypress, which restores findByRole and findByLabelText.
  • cy.origin() is a boundary, not a rename. A Playwright test that walks two domains in one flat sequence becomes a scoped callback with values passed through options and read back through aliases. The single-tab limitation has no workaround at all and the affected tests have to be redesigned rather than ported.
  • Anything Node-side becomes a cy.task(). The test body runs in the browser, so a database reset, a filesystem read, or an SMTP check has to be registered in setupNodeEvents. This is the gap that surprises teams most, because in Playwright the same call was simply an await.
  • The move buys the runner and costs reach. The live runner with DOM snapshots and the guaranteed in-file ordering are real gains. Free sharding, multi-tab, out-of-the-box WebKit, and non-JavaScript test code are real losses, and a migration plan that does not name them is a plan that will be surprised in month two.

Remember: A Playwright-to-Cypress migration is one conceptual rewrite surrounded by mechanical ones. The conceptual rewrite is the execution model: Cypress queues, Playwright runs. Everything that follows from it โ€” no await, aliases instead of variables, .then() to read and .should() to retry, cy.task() for anything the browser cannot reach โ€” is a consequence rather than a separate rule. The mechanical rewrites are vocabulary: locators to cy.get, page.route to cy.intercept, request to cy.request, storageState to cy.session. Do the conceptual rewrite first, because a file that still contains an await is not a partially migrated file, it is a file whose commands run in an order nobody designed.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!