Playwright 29 ๐ญ Migration from Cypress โ Selector strategies, retry differences, and trade-offs
Cypress and Playwright look similar at the surface โ both are test runners with a describe/it shape, both drive a real browser, both have a baseUrl and a network interceptor โ but they are built on opposite architectural assumptions. Cypress runs inside the browser, in the same run loop as the application under test, and it queues commands instead of returning promises. Playwright runs outside the browser, drives it through a protocol, and returns real promises from every call.
That difference is not cosmetic. It decides how selectors are resolved, when retries happen, what the debugging artifact looks like, and which testing scenarios are possible without workarounds. A team moving from Cypress to Playwright and writing Cypress-shaped code in Playwright will spend the first month fighting the retry model and the missing await, and blaming the tool for the friction.
This chapter is the migration. It starts with the selector model โ cy.get() to locators, data-cy to data-testid, .within() to chained locators, and the iframe gap. Then it covers the retry model, which is the single most important thing to understand before rewriting anything: Cypress retries a command chain that ends in an assertion, while Playwright re-resolves a lazy locator on every action and auto-retries expect(locator). The third section moves the supporting machinery โ cy.intercept, cy.fixture, cy.task, cy.request, cy.session, cy.clock, and custom commands โ onto the Playwright equivalents. The chapter closes with the trade-offs that should be acknowledged rather than papered over.
Key point: The migration is not a rename; it is a model change. Cypress yields a subject down a serial command queue, so retries are attached to the assertion at the end of a chain. Playwright holds a lazy locator that re-queries the DOM at the moment of each action, so retries are attached to the action itself and to every expect(locator). Rewrite the selectors first, then the retry assumptions, and leave cy.wait() behind.
Why the migration matters
The in-band architecture. Cypress executes the test code and the application code in the same browser context. That is what makes time-travel debugging possible โ the runner holds the application’s state, so it can snapshot it. It is also what makes the runner fragile: a long synchronous operation in the app can block the test runner, the two share a JavaScript heap, and the run loop is the same one. Playwright’s test code lives in Node and speaks to the browser over a protocol, so the browser’s main thread is never executing test assertions.
The single-origin limitation. For most of its history Cypress could only visit one origin per test, and cross-origin work needed the cy.origin() wrapper with its own callback, its own baseUrl, and its own restrictions. Playwright has no such boundary: page.goto() any origin, from any test, tuple-free. For a story that goes from a login on auth.example.com to a checkout on shop.example.com, this is a structural difference, not an ergonomic one.
The multi-tab gap. Cypress is designed around a single page. Opening a second tab breaks the cy chain, because the chain’s $ subject belongs to the first document. Playwright exposes the browser context and its pages directly โ context.pages(), context.newPage(), context.on('page') โ so a target="_blank" link, an OAuth popup, and a payment redirect are ordinary test steps.
The queue-versus-promise model. Cypress commands are queued and enqueued in order, and the test body is not async. cy.get() returns a chainable object, not a promise; the runner drives the queue. Playwright is ordinary async JavaScript. Every call returns a promise, and forgetting await silently discards the action โ the locator never fires, but the test still passes. That is the single most common migration bug, and it is the one the Playwright ESLint plugin exists to catch.
The retry model difference. Cypress’s retry-ability applies to the chain that ends in an assertion: cy.get('.row').should('have.length', 3) re-runs the query and the assertion until the timeout, and it is the last query in the chain that is retried. Playwright’s retry-ability is attached to the locator, which is resolved fresh at each interaction, and to expect(locator), which polls. A cy.get().click() and a page.getByRole(...).click() look identical, but only the second one re-resolves the element after it was detached mid-action.
The trade-off. Cypress’s interactive runner remains the nicest authoring environment of the two โ you open the app, click through the steps, and the command log tells you what ran. Playwright’s trace viewer is a post-hoc artifact and the analogue is only available after the fact. Cypress’s component testing is mature; Playwright’s is still flagged experimental. Cypress bundles everything into one tool; Playwright exposes the pieces. Neither model is strictly better, and the migration should be argued on the specific constraints โ parallelization cost, browser coverage, multi-origin flows, language support โ rather than on a feature checklist.
a. The selector model โ cy.get() to locators
Cypress’s default selector is a CSS string. The data-cy attribute is a convention from the Cypress docs rather than something the tool enforces, and cy.get('[data-cy=save]') is what a Cypress test looks like after that convention is adopted.
Playwright’s default is data-testid, and its recommended selectors are the accessibility-based ones: getByRole, getByLabel, getByPlaceholder, getByText, getByAltText, getByTitle, and getByTestId. These resolve against the DOM the way an assistive technology would, which is why they survive a refactor that renames a CSS class.
// tests/save-button.spec.ts
import { test, expect } from '@playwright/test';
test('saves the form', async ({ page }) => {
// Cypress: cy.visit('/form')
await page.goto('/form');
// Cypress: cy.get('[data-testid=email]').type('a@b.c')
await page.getByTestId('email').fill('a@b.c');
// Cypress: cy.get('button').contains('Save').click()
// getByRole matches the accessible name; a CSS query would not
await page.getByRole('button', { name: 'Save' }).click();
// Cypress: cy.contains('Order confirmed').should('be.visible')
await expect(page.getByText('Order confirmed')).toBeVisible();
});
A Cypress codebase that chose data-cy has two options: rewrite the attributes, or keep them and tell Playwright what the test-id attribute is called. The second option buys a mechanical migration.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// every getByTestId() in the suite now resolves data-cy
testIdAttribute: 'data-cy',
},
});
The other Cypress queries have direct equivalents. cy.contains(text) becomes getByText(text) or, when the text is a button label, getByRole('button', { name: text }). cy.contains(selector, text) becomes page.locator(selector, { hasText: text }). .eq(n) becomes .nth(n), .first() and .last() are identical, and .find() becomes a chained locator.
// Cypress: cy.get('.list').find('li').eq(2).should('have.text', 'third')
await expect(
page.locator('.list').getByRole('listitem').nth(2)
).toHaveText('third');
// Cypress: cy.get('tr').contains('td', 'Alice').parent().find('button').click()
await page
.getByRole('row')
.filter({ hasText: 'Alice' }) // narrow the row first
.getByRole('button', { name: 'Edit' }) // then the button inside it
.click();
.filter() is the replacement for cy.contains(selector, text).closest() and for .within(). It narrows a set rather than selecting a child, which reads better than a chain of .parent() and .find(). The one Cypress construct with no exact Playwright twin is .within() โ the Playwright equivalent is to assign the parent locator to a variable and chain from it, which is the same idea with the scoping made explicit.
The iframe gap. Cypress’s approach to an iframe is the well-known workaround: cy.get('iframe').its('0.contentDocument.body').then(cy.wrap) and an alias. Playwright ships frameLocator, which is a locator that scopes into the frame’s document and resolves fresh on each action.
// Cypress: cy.get('#checkout').its('0.contentDocument.body').then(cy.wrap)
// .find('button').click()
await page
.frameLocator('#checkout') // scope into the iframe
.getByRole('button', { name: 'Pay' })
.click();
Shadow DOM behaves the same in both: open shadow roots are pierced automatically, and closed ones are unreachable. A component in a shadow tree can be addressed directly in either tool.
b. The retry model โ queue-and-chain vs lazy locator
This is the difference that actually breaks a migrated suite, so it is worth stating precisely.
In Cypress, cy.get('.row') runs once, at the moment its turn arrives in the queue, and its result is handed to the next command as a subject. Retry-ability belongs to the assertion: when a chain ends in .should(...), Cypress re-runs the chain’s query and the assertion together until the assertion passes or defaultCommandTimeout (4 s) expires. An action such as .click() is not retried โ if the click succeeds on a stale element and the next assertion fails, Cypress does not go back and click again.
In Playwright, page.getByRole('row') performs no query at all. It builds a description of how to find the element. The query happens when the locator is used: on .click(), .fill(), .textContent(), and inside expect(locator). Before an action, Playwright waits for the element to be attached, visible, stable (not animating), enabled, and to receive pointer events. If the list re-renders mid-click and detaches the element, Playwright re-queries and retries the click โ the whole action, not just the assertion.
// Cypress: cy.get('.submit').click()
// cy.get('.toast').should('contain', 'Saved')
//
// Playwright: locators are lazy; the action re-resolves the element
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.getByRole('status')).toContainText('Saved');
The expect(locator) call is a web-first assertion. It polls the locator until the assertion passes or expect.timeout (5 s) expires. This is the direct replacement for cy.get(...).should(...).
The trap is that not every Playwright assertion retries. expect(value).toBe(...), toEqual, toBeTruthy, and toBeNull are plain value assertions โ they snapshot the value at the moment they run. If the value is a textContent() that was read before the update landed, the assertion fails immediately with no retry. When the value is derived from the page, read it through a locator assertion or through expect.poll.
// WRONG: textContent() is a one-shot read; toBe does not retry
const text = await page.getByTestId('count').textContent();
expect(text).toBe('3'); // โ
// RIGHT: toHaveText polls the locator until 3 appears or 5s expires
await expect(page.getByTestId('count')).toHaveText('3'); // โ
// RIGHT: expect.poll retries an arbitrary async function
await expect.poll(async () =>
(await page.getByTestId('count').textContent())?.trim()
).toBe('3'); // โ
cy.wait('@alias') โ the Cypress idiom for “wait for this request” โ becomes page.waitForResponse, and cy.wait(1000) has no Playwright equivalent worth having. Playwright’s auto-waiting plus a web-first assertion already covers the case cy.wait(1000) was papering over, and page.waitForTimeout() exists mostly to be linted against.
// Cypress: cy.intercept('GET', '/api/cart').as('cart')
// cy.get('[data-cy=refresh]').click()
// cy.wait('@cart')
const cartLoaded = page.waitForResponse('**/api/cart');
await page.getByTestId('refresh').click();
await cartLoaded; // โ
real request
The timeout knobs differ too, and knowing the defaults prevents a suite that hangs in one place and flakes in another.
| Timeout | Cypress default | Playwright default |
|---|---|---|
| Command / action | defaultCommandTimeout 4 000 ms | actionTimeout 0 (falls back to test timeout) |
| Assertion | shares command timeout | expect.timeout 5 000 ms |
| Navigation | pageLoadTimeout 60 000 ms | 30 000 ms |
| Test | no per-test default | 30 000 ms |
c. The supporting machinery โ network, fixtures, sessions, clock
cy.intercept is the Cypress stubbing primitive, and page.route is the Playwright one. The shapes are close enough that the rewrite is mechanical.
// Cypress: cy.intercept('GET', '/api/users', { fixture: 'users.json' })
await page.route('**/api/users', (route) =>
route.fulfill({ path: 'fixtures/users.json' })
);
// Cypress: cy.intercept('POST', '/api/order', (req) => {
// req.reply({ statusCode: 201, body: { id: 1 } })
// })
await page.route('**/api/order', (route) =>
route.fulfill({ status: 201, json: { id: 1 } })
);
// a request that is allowed through, but observed
await page.route('**/api/**', async (route) => {
requests.push(route.request().url());
await route.continue(); // not a stub
});
page.route matches with a glob, a regex, or a predicate, so a Cypress intercept that matched by method needs the method moved into the predicate rather than into the pattern.
The rest of the Cypress helper surface collapses into ordinary Node. cy.fixture() reads a file from cypress/fixtures; in Playwright, import the JSON โ the bundler and TypeScript both understand it, and the type comes along. cy.task() exists because the Cypress test body runs in the browser and therefore cannot touch the filesystem or the database; Playwright’s test body is Node, so the task function is just a function. cy.request() becomes the request fixture, which is an API client with the same baseURL as the page.
// Cypress: cy.fixture('user.json').then((user) => cy.get(...).type(user.email))
import user from '../fixtures/user.json'; // just an import
// Cypress: cy.task('resetDatabase')
import { resetDatabase } from '../support/db';
await resetDatabase(); // just a function
// Cypress: cy.request('GET', '/api/orders').its('body').should('have.length', 3)
const res = await request.get('/api/orders');
expect(res.ok()).toBeTruthy();
expect((await res.json()).length).toBe(3);
cy.session() is the Cypress cache for a login flow. Playwright’s equivalent is storageState captured once by a setup project and reused by the projects that depend on it โ which is both faster and inspectable, because the cached state is a JSON file on disk.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{ name: 'setup', testMatch: /auth\.setup\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'], // run auth first
},
],
});
Cypress.Commands.add() becomes a custom fixture, which is the Playwright idiom for shared setup with a typed, per-test lifetime.
// tests/fixtures.ts
import { test as base } from '@playwright/test';
// a typed fixture the whole suite can request by destructuring
export const test = base.extend<{ login: () => Promise<void> }>({
login: async ({ page }, use) => {
await use(async () => {
await page.goto('/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByRole('button', { name: 'Sign in' }).click();
});
},
});
cy.clock() was Cypress’s sinon fake timer. Playwright’s page.clock is the replacement, installed before navigation so the app sees the fake clock from its first line.
// Cypress: cy.clock(Date.UTC(2025, 0, 1))
await page.clock.install({ time: new Date('2025-01-01T00:00:00Z') });
await page.goto('/dashboard');
// advance 30 seconds without waiting 30 seconds
await page.clock.fastForward(30_000);
Finally, test isolation. Cypress clears cookies and local storage between tests by default (testIsolation: true, since v12) but reuses the same browser and the same cy state within a file. Playwright creates a fresh browser context per test โ new cookie jar, new cache, new localStorage, new sessionStorage โ by default. That removes an entire class of order-dependence flake, and it means the migration should delete most of the beforeEach cleanup code rather than port it.
Complete Example Session
// ============================================
// PART 1: THE CYPRESS TEST, AS WRITTEN
// ============================================
// cypress/e2e/checkout.cy.ts
// describe('checkout', () => {
// beforeEach(() => { cy.visit('/cart'); });
//
// it('pays with a saved card', () => {
// cy.intercept('POST', '/api/pay', { fixture: 'pay-ok.json' }).as('pay');
// cy.get('[data-cy=pay]').click();
// cy.wait('@pay');
// cy.contains('Order confirmed').should('be.visible');
// });
// });
// ============================================
// PART 2: THE PLAYWRIGHT SCAFFOLD
// ============================================
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
use: {
baseURL: 'http://localhost:3000', // replaces Cypress baseUrl
testIdAttribute: 'data-cy', // keep the existing attribute
trace: 'on-first-retry', // replaces the runner's time travel
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});
// ============================================
// PART 3: THE SELECTOR REWRITE
// ============================================
// tests/checkout.spec.ts
import { test, expect } from '@playwright/test';
test('pays with a saved card', async ({ page }) => {
await page.goto('/cart'); // cy.visit('/cart')
// ============================================
// PART 4: THE NETWORK STUB
// ============================================
await page.route('**/api/pay', (route) =>
route.fulfill({ path: 'tests/fixtures/pay-ok.json' })
);
// ============================================
// PART 5: THE WAIT-FOR-RESPONSE REPLACEMENT
// ============================================
const payResponse = page.waitForResponse('**/api/pay');
await page.getByTestId('pay').click();
await payResponse; // cy.wait('@pay')
// ============================================
// PART 6: THE ASSERTION
// ============================================
// auto-retries for up to 5s; no cy.contains().should() needed
await expect(page.getByText('Order confirmed')).toBeVisible();
});
// ============================================
// PART 7: THE AUTH FIXTURE (cy.session)
// ============================================
// tests/fixtures.ts
import { test as base, expect } from '@playwright/test';
export const test = base.extend<{ login: () => Promise<void> }>({
login: async ({ page }, use) => {
await use(async () => {
await page.goto('/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL(/\/dashboard/); // waits for navigation
});
},
});
export { expect };
// ============================================
// PART 8: THE CLOCK (cy.clock)
// ============================================
// tests/expiry.spec.ts
import { test, expect } from './fixtures';
test('shows the session as expired', async ({ page, login }) => {
await page.clock.install({ time: new Date('2025-01-01T00:00:00Z') });
await login();
await page.clock.fastForward('02:00:00'); // jump two hours
await expect(page.getByText('Session expired')).toBeVisible();
});
// ============================================
// PART 9: THE MULTI-ORIGIN FLOW (cy.origin)
// ============================================
test('pays on a separate origin', async ({ page }) => {
await page.goto('https://auth.example.com/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByRole('button', { name: 'Sign in' }).click();
// no cy.origin() wrapper; the origin boundary is invisible
await page.goto('https://shop.example.com/checkout');
await page.getByRole('button', { name: 'Pay' }).click();
});
// ============================================
// PART 10: THE PARALLEL RUN
// ============================================
// $ npx playwright test --workers=4
// $ npx playwright test --shard=1/3
// both are free; Cypress needs the Cloud (or sorry-cypress) for this
The ten parts covered the Cypress original, the Playwright config with baseURL and testIdAttribute, the selector rewrite, the page.route stub, the waitForResponse replacement for cy.wait('@alias'), the auto-retrying assertion, the auth fixture replacing cy.session, the page.clock replacement for cy.clock, the multi-origin flow without cy.origin, and free parallelization.
Quick Reference
Selector mapping
| Cypress | Playwright |
|---|---|
cy.get('[data-cy=x]') | page.getByTestId('x') |
cy.contains('Save') | page.getByText('Save') |
cy.get('button').contains('Save') | page.getByRole('button', { name: 'Save' }) |
.eq(n) / .first() / .last() | .nth(n) / .first() / .last() |
.find('.x') | .locator('.x') or .getByRole(...) |
.within($el) | assign the parent locator and chain |
.parent().find('button') | .filter({ hasText }) then .getByRole('button') |
Command mapping
| Cypress | Playwright |
|---|---|
cy.visit(url) | page.goto(url) |
cy.intercept(...) | page.route(...) |
cy.wait('@alias') | page.waitForResponse(...) |
cy.fixture('f.json') | import f from './f.json' |
cy.task('name') | ordinary Node function |
cy.request(...) | request.get(...) |
cy.session(...) | storageState + setup project |
Cypress.Commands.add() | test.extend({ ... }) |
cy.clock() | page.clock.install() |
Retry model
| Concept | Cypress | Playwright |
|---|---|---|
| Query timing | once per chain | every action |
| Retry scope | chain ending in assertion | each action + expect(locator) |
| Non-retrying | โ | toBe, toEqual, toBeTruthy |
| Poll an arbitrary value | cy.then loop | expect.poll() |
Timeouts
| Knob | Cypress | Playwright |
|---|---|---|
| Command / action | 4 000 ms | 0 (test timeout) |
| Assertion | 4 000 ms | 5 000 ms |
| Navigation | 60 000 ms | 30 000 ms |
| Test | none | 30 000 ms |
Best Practices
โ Do This:
// Await every Playwright call
await page.getByRole('button', { name: 'Save' }).click(); // โ
// Let the locator assertion retry
await expect(page.getByTestId('count')).toHaveText('3'); // โ
// Keep data-cy by declaring the attribute
use: { testIdAttribute: 'data-cy' } // โ
// Prefer role-based locators over CSS classes
page.getByRole('button', { name: 'Save' }) // โ
// Replace cy.wait('@x') with waitForResponse
const r = page.waitForResponse('**/api/x'); await click(); await r; // โ
// Delete beforeEach cleanup; each test gets a fresh context
// (no cookies, cache, or localStorage leak) // โ
// Cache auth with storageState and a setup project
dependencies: ['setup'], use: { storageState: 'auth.json' } // โ
โ Don’t Do This:
// Forget await โ the action never fires and the test still passes
page.getByRole('button', { name: 'Save' }).click(); // โ
// Read a value, then assert without retry
expect(await page.getByTestId('n').textContent()).toBe('3'); // โ
// Port cy.wait(1000) as waitForTimeout
await page.waitForTimeout(1000); // โ
// Keep the cy.origin() ceremony
await page.goto('https://a.com'); /* cy.origin would go here */ // โ
// Port the iframe workaround
await page.locator('iframe').evaluate((f) => f.contentDocument) // โ
// Keep cy.session-style caching in beforeEach
test.beforeEach(async ({ page }) => { await login(page); }); // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Test “passes” but does nothing | await omitted | ESLint no-floating-promises |
| Assertion never retries | Read value then toBe | expect(locator).toHaveX() or expect.poll |
| Selector not found | data-testid vs data-cy | Set testIdAttribute: 'data-cy' |
| Stale element click | Cypress thinking โ action not retried | Playwright already re-resolves |
| Flaky after migration | waitForTimeout ported | Use expect / waitForResponse |
| Auth cached badly | cy.session ported to beforeEach | storageState + setup project |
| Cross-origin step fails | cy.origin callback copied | Plain page.goto |
| Tests order-dependent | Shared state kept in globals | Fresh context per test |
Real-World Examples
1. Selector rewrite
await page.getByRole('button', { name: 'Save' }).click();
2. Keep data-cy
use: { testIdAttribute: 'data-cy' }
3. Network stub
await page.route('**/api/users', (r) => r.fulfill({ json: users }));
4. Wait for a response
const r = page.waitForResponse('**/api/x');
await page.getByTestId('go').click();
await r;
5. Retrying assertion
await expect(page.getByTestId('count')).toHaveText('3');
6. Poll a value
await expect.poll(async () => (await page.textContent('#n'))?.trim()).toBe('3');
7. Fixture for login
login: async ({ page }, use) => { await use(async () => { /* ... */ }); }
8. Fake clock
await page.clock.install({ time: new Date('2025-01-01') });
9. Frame locator
await page.frameLocator('#pay').getByRole('button', { name: 'Pay' }).click();
10. Shard the suite
npx playwright test --shard=1/3
Visual
Cypress to Playwright selectors
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CYPRESS โ PLAYWRIGHT SELECTORS โ
โ โ
โ cy.get('[data-cy=save]') โ
โ โ page.getByTestId('save') โ
โ โ
โ cy.contains('Save') โ
โ โ page.getByText('Save') โ
โ โ
โ cy.get('button').contains('Save') โ
โ โ page.getByRole('button', { name: 'Save' }) โ
โ โ
โ cy.get('form').find('input') โ
โ โ page.locator('form').getByRole('textbox') โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The retry model
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CYPRESS: QUEUE AND CHAIN โ
โ โ
โ cy.get('.row') query runs once โ
โ .should('have.length', 3) retries the query โ
โ .click() action runs once โ
โ โ
โ PLAYWRIGHT: LAZY LOCATOR โ
โ โ
โ loc = page.getByRole('row') no query yet โ
โ await loc.click() re-queries, waits, clicks โ
โ await expect(loc).toHaveCount(3) polls โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The supporting machinery
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CYPRESS PLAYWRIGHT โ
โ โ
โ cy.intercept() page.route() โ
โ cy.fixture('u.json') import u from './u.json' โ
โ cy.task('seed') await seed() // plain Node โ
โ cy.request() request.get() // fixture โ
โ cy.session() storageState // project โ
โ Cypress.Commands.add() test.extend({ ... }) โ
โ cy.visit('/') page.goto('/') โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The trade-off matrix
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DIMENSION CYPRESS PLAYWRIGHT โ
โ โ
โ Languages JS / TS JS/TS, Py, Java, .NET โ
โ Engines Chromium, FF Chromium, FF, WebKit โ
โ Parallel Cloud (paid) workers, --shard โ
โ Debugging live runner trace viewer โ
โ Multi-origin cy.origin() native โ
โ Multi-tab no yes โ
โ Retry model query+assertion every action โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Default test id | data-testid (Cypress: data-cy) |
| Override | use: { testIdAttribute: 'data-cy' } |
| Recommended selector | getByRole (Cypress: cy.get) |
| Query timing | Lazy โ resolves per action |
| Retry scope | Each action + expect(locator) |
| Non-retrying | toBe, toEqual, toBeTruthy |
| Poll | expect.poll() |
| Network stub | page.route (Cypress: cy.intercept) |
| Network wait | page.waitForResponse (Cypress: cy.wait('@a')) |
| Auth cache | storageState + setup project |
| Clock | page.clock (Cypress: cy.clock) |
| Isolation | Fresh context per test |
Key takeaways:
- The
awaitis not optional and its absence is silent. Cypress queues commands; there is nothing to await. Playwright returns promises from every call, and an un-awaitedclick()never fires while the test still reports green. Turn on@typescript-eslint/no-floating-promisesbefore the migration starts, not after. - Playwright’s locator is lazy.
page.getByRole('row')performs no query. The query happens at each.click(),.fill(), and insideexpect(locator), and it is re-run if the element detaches mid-action. Cypress’scy.get()runs once and passes the subject down the chain; that is why Cypress needs.should()to retry and Playwright does not. - Only locator assertions retry.
expect(locator).toBeVisible(),.toHaveText(),.toHaveCount()poll until the timeout.expect(value).toBe()does not. A read-then-assert pattern (textContent()thentoBe) is a guaranteed flake and is the most common artifact of a Cypress port. cy.wait('@alias')becomespage.waitForResponse, notwaitForTimeout. The Cypress pattern of intercepting and then waiting is a two-line Playwright sequence โ start thewaitForResponsepromise, click, await the promise โ and it costs nothing to get right.cy.originand the iframe workaround both vanish. Playwright drives the browser out of process, so a second origin is apage.goto, a second tab iscontext.newPage(), and an iframe isframeLocator. The workarounds existed because Cypress ran inside the page; Playwright does not.cy.sessionbecomesstorageState, andcy.taskbecomes a function. The Cypress test body ran in the browser, which is why it needed a Node bridge. The Playwright test body is Node, so fixtures, database resets, and file reads are ordinaryimports andawaits.- The trade-off is real, and the migration should name it. Cypress’s interactive runner is still the better authoring experience, and its component testing is mature where Playwright’s is experimental. Playwright wins on multi-origin, multi-tab, browser coverage, free parallelization, and free sharding โ and the trace viewer is a fine replacement for time travel after the fact, even if it is not one during authoring.
Remember: A Cypress migration is two rewrites in sequence. The first is mechanical โ selectors, page.route, waitForResponse, page.clock, storageState โ and it can be done file by file with the suite still green. The second is conceptual, and it is where the time goes: internalize that Playwright’s locator re-resolves on every action, that only locator assertions retry, and that await is load-bearing. Do the mechanical rewrite second and the conceptual rewrite first, and the new suite behaves like Playwright rather than like Cypress with different syntax. Skip it, and the flake you migrated away from follows you across.
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!