Run Web Automation Tests at Scale with Agentic AI
Generate tests with AI agents or automate test suites with Selenium, Playwright and other frameworks. Run tests in parallel on TestMu AI scalable cloud grid.
Cypress to Playwright Migration: A Step-by-Step Guide
Migrate from Cypress to Playwright with a full cy.* API mapping table, a nine-step procedure, config translation, and the commands that do not convert.
Last Updated on:
Migrating from Cypress to Playwright is mostly a mechanical translation, and an automated converter will get you a long way through it. What catches teams out is not the syntax. It is the three or four places where a line-for-line conversion compiles, runs, and quietly means something different from the test you started with.
This guide gives you the full command mapping, a migration order that keeps your suite green throughout, and an honest account of what no converter will handle for you. If you have not yet decided whether to move at all, the Cypress vs Playwright comparison covers that decision first.
TL;DR
- Run both frameworks side by side during the migration. They use separate configs and directories, so there is no reason to cut over in one step.
- Playwright strict mode is the biggest single source of first-run failures: a locator matching more than one element throws, where Cypress silently carried on.
- If your suite uses data-cy attributes, set testIdAttribute in the config or every getByTestId call will match nothing.
- cy.intercept does not map cleanly onto page.route. Method filtering and request waiting both have to be rebuilt by hand.
- Custom commands, .within, .each, cy.task and the alias system have no direct equivalents and need redesign, not translation.
- Port specs by fragility and value, not by folder. Cross-origin, multi-tab and Safari-dependent tests gain the most and should go first.
Should You Migrate from Cypress to Playwright?
Migration is worth the effort when you are hitting an architectural wall rather than a preference. Cypress runs inside the browser, which is the source of both its best feature, time-travel debugging, and its hardest limits. If none of those limits affect you, a working Cypress suite is not a problem that needs solving. If you stay, the Cypress 16.3 release post covers the current upgrade path.
The clear triggers for migrating are:
- Safari and WebKit coverage. Playwright ships WebKit as a first-class engine. Cypress supports it experimentally.
- Multi-tab and cross-origin flows. Playwright handles multiple tabs, windows and origins natively, where Cypress needs cy.origin and cannot switch tabs at all.
- Parallelisation cost. Playwright shards across workers and machines for free. Cypress parallel orchestration is a paid Cypress Cloud feature. Free ways to split Cypress specs are compared in Cypress parallelization.
- Mixed-language teams. Playwright has official bindings for JavaScript, TypeScript, Python, Java and C#. Cypress is JavaScript and TypeScript only.
- CI wall-clock time. Playwright has lower per-spec startup overhead, which compounds across suites made of many short specs.
If your application is a single-domain app, your team is productive, and CI is fast enough, there is no urgency. Migration costs real engineering time and introduces fresh flaky tests while the new suite settles.
Before You Start
Install Playwright alongside Cypress rather than replacing it. The two runners do not conflict: different config files, different test directories, different CLI entry points.
There is one exception, and it bites on day one of a TypeScript migration. Cypress and @playwright/test both ship ambient global declarations for describe, it and expect, so a single tsconfig covering both trees produces duplicate-identifier errors. Give each suite its own tsconfig and scope it to that directory, rather than trying to make one config serve both. The Playwright 1.65 release guide covers a separate TypeScript change to class fields in page objects.
npm init playwright@latestThe installer creates a tests directory, a playwright.config.ts, and downloads the browser binaries. Point it at a new folder such as tests-pw so it does not collide with your existing cypress/e2e tree.
Three decisions are worth making before you port a single spec, because changing them later means touching every file:
- Your test-id attribute. Playwright getByTestId reads data-testid by default. If your suite uses data-cy or data-test, set testIdAttribute in the config now.
- Locator strategy. Playwright recommends role, label and test-id locators over raw CSS. Converting cy.get('.css-class') to page.locator('.css-class') works, but you lose most of the reliability benefit.
- Where shared setup lives. Cypress custom commands become either fixtures or page object model classes. Pick one before you port login.
Note: Run your migrated Playwright suite across 3000+ real browsers and OS combinations. Try TestMu AI Today!
Cypress to Playwright API Mapping
This is the reference table most migrations run on. The third column is the one that matters: a mapping marked Needs care compiles and runs but does not mean the same thing as the Cypress line it replaced.
Navigation and Element Selection
| Cypress | Playwright | Notes |
|---|---|---|
| cy.visit('/products') | await page.goto('/products') | Needs care. cy.visit fails the test on a non-2xx response. page.goto does not throw on 404 or 500, so you silently lose an assertion. |
| cy.get('.submit') | page.locator('.submit') | Needs care. Strict mode: if this matches more than one element, any action throws. Cypress happily held all of them. |
| cy.get('[data-cy=add]') | page.getByTestId('add') | Needs care. Only works if you set testIdAttribute: 'data-cy' in the config. Otherwise it reads data-testid and matches nothing. |
| cy.contains('Checkout').click() | await page.getByRole('link', { name: 'Checkout' }).click() | Needs care. cy.contains yields at most one element. getByText matches every ancestor containing the text, which usually triggers a strict mode violation. Use a role locator. |
| cy.contains('Save') | page.getByText('Save', { exact: true }) | Needs care. Both are substring matches by default, so both also match "Save draft". Cypress is case-sensitive; Playwright is case-insensitive unless exact is set. |
| cy.get('.card').find('.price') | page.locator('.card').locator('.price') | Needs care. Shape is right, cardinality is not. Scope with .filter() before acting. |
| cy.go('back') / cy.reload() | await page.goBack() / await page.reload() | Clean. |
Interactions
| Cypress | Playwright | Notes |
|---|---|---|
| .click() | await locator.click() | Clean. Playwright waits for actionability automatically. |
| .click({ force: true }) | await locator.click({ force: true }) | Clean, and equally suspect in both frameworks. |
| .type('hello') | await locator.fill('hello') | Needs care. fill() sets the value in one step. Use pressSequentially() only when the app depends on per-keystroke events. |
| .type('{enter}') | await locator.press('Enter') | Clean. |
| .clear() | await locator.clear() | Clean. |
| .select('apples') | await locator.selectOption('apples') | Clean. Both match on option value or visible label. |
| .check() / .uncheck() | await locator.check() / .uncheck() | Needs care. cy.get(':checkbox').uncheck() unchecks every match. Playwright throws on more than one. Loop explicitly. |
| .trigger('mouseover') | await locator.hover() | Clean, and more faithful than the Cypress original. |
| cy.viewport(1280, 720) | await page.setViewportSize({ width: 1280, height: 720 }) | Clean. Prefer setting it in the config or via test.use(). |
Assertions
This is where mechanical conversion introduces flakiness. In Cypress, assertions retry the whole chain, for as long as the Cypress timeout settings allow. In Playwright, expect(locator) auto-retries but expect(value) does not. Converting a .should() into an assertion on an already-resolved value removes the retry you were relying on.
| Cypress | Playwright | Notes |
|---|---|---|
| .should('be.visible') | await expect(locator).toBeVisible() | Needs care. On a multi-element subject Cypress means "at least one is visible". Use .filter({ visible: true }).not.toHaveCount(0) to preserve that. |
| .should('not.exist') | await expect(locator).toHaveCount(0) | Needs care. toBeHidden() passes for an element that exists but is hidden. toHaveCount(0) is the faithful mapping. |
| .should('have.text', 'Hi') | await expect(locator).toHaveText('Hi') | Clean. |
| .should('contain', 'Keyboard') | await expect(locator.filter({ hasText: 'Keyboard' })).not.toHaveCount(0) | Needs care. Cypress means "at least one match". toHaveCount(1) would assert exactly one and fail wrongly. |
| .should('have.value', 'x') | await expect(locator).toHaveValue('x') | Clean. |
| .should('have.class', 'price') | await expect(locator).toContainClass('price') | Needs care. Requires Playwright 1.52+. Do not fall back to toHaveClass(/\bprice\b/), which false-positives on BEM names like price--lg. |
| .should('have.attr', 'href') | await expect(locator).toHaveAttribute('href') | Clean. |
| .should('be.disabled') | await expect(locator).toBeDisabled() | Clean. |
| cy.url().should('include', '/app') | await expect(page).toHaveURL(/\/app/) | Clean. |
| cy.title().should('eq', 'Home') | await expect(page).toHaveTitle('Home') | Clean. |
How to Migrate from Cypress to Playwright
The order below keeps your existing suite authoritative until the replacement is genuinely green. Do not delete Cypress specs as you go.
- Step 1. Install Playwright alongside Cypress. Separate directory, separate config, both running in CI.
- Step 2. Translate the config first. baseURL, viewport, retries, reporters and Playwright timeouts. Getting this right removes a whole class of per-spec edits later.
- Step 3. Freeze new Cypress tests. From this point, new specs are written in Playwright. Otherwise you are migrating a moving target.
- Step 4. Build the auth setup project. Port login once, as a setup project writing storageState. Almost every spec depends on it.
- Step 5. Convert custom commands into fixtures or page objects. Do this before bulk-porting specs, since every spec references them.
- Step 6. Port specs by fragility, not by folder. Start with cross-origin, multi-tab and Safari-dependent tests. They gain the most and prove the migration is worth it.
- Step 7. Fix strict mode violations as they surface. Expect these on the first run of nearly every ported spec. They are revealing real ambiguity in your selectors.
- Step 8. Run both suites in parallel for a few days. Compare results. A Playwright test that passes while its Cypress twin fails deserves investigation before you trust it.
- Step 9. Retire each Cypress spec only after its replacement has been stable. Delete in batches, not all at once.
A Spec Before and After
The same login flow in Cypress:
describe('Login', () => {
beforeEach(() => {
cy.visit('/login');
});
it('signs the user in', () => {
cy.get('[data-cy=email]').type('user@example.com');
cy.get('[data-cy=password]').type('secret');
cy.contains('button', 'Sign in').click();
cy.url().should('include', '/dashboard');
cy.get('[data-cy=welcome]').should('contain', 'Welcome back');
});
});And in Playwright, assuming testIdAttribute is set to data-cy in the config:
const { test, expect } = require('@playwright/test');
test.describe('Login', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/login');
});
test('signs the user in', async ({ page }) => {
await page.getByTestId('email').fill('user@example.com');
await page.getByTestId('password').fill('secret');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL(/\/dashboard/);
await expect(page.getByTestId('welcome')).toContainText('Welcome back');
});
});Note what changed beyond syntax: cy.contains('button', 'Sign in') became a role locator rather than a text locator, because matching on text alone would have matched the button and its wrapper and thrown a strict mode violation.
Custom Commands Become Fixtures
Step 5 is the one that gates every other spec, so it is worth doing concretely. A Cypress custom command is a global registration; a Playwright fixture is a dependency injected into the tests that ask for it. Note that extend() takes a single object, and the helper is handed to the test through use().
// fixtures.js
import { test as base, expect } from '@playwright/test';
export const test = base.extend({
login: async ({ page }, use) => {
await use(async (email, password) => {
await page.goto('/login');
await page.getByTestId('email').fill(email);
await page.getByTestId('password').fill(password);
await page.getByRole('button', { name: 'Sign in' }).click();
});
},
});
export { expect };Specs then import from your fixtures file instead of from @playwright/test, and the helper arrives as an argument:
import { test, expect } from './fixtures';
test('adds an item to the cart', async ({ page, login }) => {
await login('user@example.com', 'secret');
await page.getByTestId('add-to-cart').click();
await expect(page.getByTestId('cart-count')).toHaveText('1');
});For commands that wrap a specific screen rather than perform setup, a page object model class is usually the better fit.
Translating cypress.config.js to playwright.config.ts
| cypress.config.js | playwright.config.ts |
|---|---|
| e2e.baseUrl | use.baseURL |
| viewportWidth / viewportHeight | use.viewport |
| defaultCommandTimeout | expect.timeout (assertions) and use.actionTimeout (actions) |
| pageLoadTimeout | use.navigationTimeout |
| retries | retries |
| video | use.video |
| screenshotOnRunFailure | use.screenshot |
| env | Plain process.env, or the projects use block |
| specPattern | testDir and testMatch |
| supportFile | No equivalent. Use fixtures or globalSetup. |
| (no equivalent) | testIdAttribute — set this if you use data-cy |
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests-pw',
fullyParallel: true,
retries: process.env.CI ? 2 : 0,
forbidOnly: !!process.env.CI,
reporter: [['html'], ['list']],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
testIdAttribute: 'data-cy',
viewport: { width: 1280, height: 720 },
screenshot: 'only-on-failure',
video: 'retain-on-failure',
trace: 'on-first-retry',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});One line there deserves attention. fullyParallel: true is in the default scaffold and it changes behaviour Cypress users rely on: tests within a single file run concurrently, each in its own browser context. Cypress runs a spec file top to bottom in one browser, so any spec whose later tests quietly depend on state set by earlier ones will fail. That is usually a latent bug worth fixing, but if you need the old behaviour while migrating, set it to false or mark the file with test.describe.serial().
On the CLI, cypress run --spec becomes npx playwright test with a path, --browser becomes --project, and Cypress Cloud parallelisation becomes --workers locally or --shard across machines, both free.
Network Mocking: cy.intercept to page.route
This is the single most error-prone part of the migration, and the part automated converters handle worst. Two things break.
For a quick visual walkthrough of this concept, watch the video below from TestMu AI.
Subscribe to the TestMu AI YouTube channel for more tutorials on testing and automation.
First, the method filter disappears. cy.intercept takes the HTTP method as its first argument. page.route matches on URL only, so a naive conversion stubs every verb against that URL, including the GET that populates the page.
// Cypress: only PUT is stubbed
cy.intercept('PUT', '/users', { statusCode: 200, body: {} }).as('save');
// Playwright: the method check must move inside the handler
await page.route('**/users', async route => {
if (route.request().method() !== 'PUT') {
await route.fallback();
return;
}
await route.fulfill({ status: 200, json: {} });
});Second, aliases and cy.wait have no equivalent. Playwright has no alias registry. You wait with page.waitForRequest or page.waitForResponse, and critically, the wait must be armed before the action that triggers it.
// Cypress
cy.intercept('POST', '/api/items').as('addItem');
cy.get('[data-cy=add]').click();
cy.wait('@addItem');
// Playwright: arm the wait first, then act
const addItem = page.waitForRequest(
r => r.url().includes('/api/items') && r.method() === 'POST'
);
await page.getByTestId('add').click();
await addItem;For plain API calls, cy.request becomes page.request. Keep the verb: cy.request defaults to GET, so converting it to page.request.post() changes the call.
Authentication: cy.session to storageState
Cypress caches a login with cy.session. Playwright's equivalent is to log in once in a setup project, save the browser state to disk, and have every other project load it.
// auth.setup.js
import { test as setup, expect } from '@playwright/test';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByTestId('email').fill(process.env.TEST_USER);
await page.getByTestId('password').fill(process.env.TEST_PASS);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL(/\/dashboard/);
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});Then wire it up in the config so authentication runs once before the suite rather than once per spec. The setup project runs first; every other project declares it as a dependency and loads the saved state:
projects: [
{ name: 'setup', testMatch: /.*\.setup\.js/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
],Add playwright/.auth to .gitignore. The file holds live session cookies. The guide to Playwright best practices pairs this one-time login with rules that keep every test independent.
What Does Not Convert
These are the items that make migration estimates wrong. None of them is a syntax swap; each needs a design decision.
| Cypress feature | Why it does not convert | Replacement |
|---|---|---|
| Cypress.Commands.add | Playwright has no global command registry. | A test fixture, or a page object method. |
| Cypress.Commands.overwrite | Nothing to overwrite. | Wrap the call in your own helper. |
| .within() | Converts mechanically, but the scope becomes a locator rather than a retrying context. | Chain locators: form.getByLabel('Email'). |
| .each() | The genuinely unsupported one. Converters either omit it or refuse the whole category as too complex. | A for-of loop over await locator.all(). |
| .then() chains on jQuery elements | Cypress yields jQuery objects through a command queue. Playwright locators are lazy and resolved with await. | Await the locator method you need, or locator.evaluate() for real DOM properties. |
| cy.task() | No browser-side Node bridge. | Run Node code directly in a fixture or globalSetup. |
| cy.exec() | Removed in Cypress 16 itself, so newer suites will not have it. Older ones still need translating. | Node child_process inside a fixture or globalSetup. |
| cy.origin() | Not needed. | Playwright handles cross-origin natively; delete the wrapper. |
| Aliases (.as) and cy.wait('@x') | No alias registry. | page.waitForRequest / waitForResponse, armed before the action. |
| Cypress plugins | Separate ecosystems. | Most have Playwright counterparts; file upload and accessibility checks are built in or first-party. |
| Implicit retryability | Cypress retries queued commands. Playwright is plain async/await. | Rely on web-first assertions; never assert on an already-resolved value. |
| Shared state between tests | Cypress runs tests in one browser, so cookies and localStorage can survive from one test to the next. Playwright gives every test a fresh browser context. | Nothing to port, but specs that implicitly depended on leaked state will fail. Set state explicitly, or load it from storageState. |
| window and document access | Cypress test code runs inside the browser. Playwright runs in Node, so there is no ambient window. | page.evaluate() when you genuinely need the DOM — and you gain direct filesystem and database access in exchange. |
The one that surprises teams most is the last. A mechanically converted .then() chain still runs, but the retry behaviour it depended on is gone, and the result is a suite that is subtly flakier than the one you replaced. When a converted step waits too long, timeout of 30000ms exceeded shows how Cypress and Playwright word the timeout.
What Replaces the Cypress App
The objection most Cypress users raise is not about syntax. It is that the Cypress App, with its time-travel debugging and live command log, is genuinely good and they do not want to lose it. Playwright does not have a single equivalent. It has four separate tools, and together they cover more ground.
- UI Mode — npx playwright test --ui. The closest thing to the Cypress App: a watch-mode runner with a time-travel timeline, per-step DOM snapshots, and the ability to re-run a single test on save. This is the one to show a sceptical team first.
- Trace Viewer — npx playwright show-trace. An after-the-fact recording of a run: every action, DOM snapshots before and after, network log, console output and source. Because traces are files, this works for CI failures, which is where Cypress debugging is weakest.
- Codegen — npx playwright codegen. Records your clicks into generated test code using role and test-id locators. Useful during migration for seeing how Playwright would express a flow you are hand-porting.
- The Inspector — PWDEBUG=1. Steps through a test with a live locator explorer for working out why a selector does not match.
Set trace to 'on-first-retry' in the config, as the example above does, and every flaky CI failure arrives with a full recording attached. That is the capability Cypress users most often discover they prefer.
Automated Cypress to Playwright Converters
The most capable converter is cy2pw, hosted on playwright.dev and originally written by Playwright's co-creator. It is a real Babel AST codemod rather than a find-and-replace, it runs entirely client-side, and it maps around 78 Cypress commands including within, then, wrap, invoke, its, request and the Testing Library findBy* family.
One caveat that matters for planning: despite the playwright.dev address, cy2pw is not maintained. Its repository was archived in September 2025 and has not changed since October 2023, so it knows nothing about Playwright APIs added since. The tool still runs and is still the best starting point, but treat it as a frozen utility rather than a supported product. Community alternatives on GitHub are narrower, not equivalent — the most popular one maps roughly 30 commands and explicitly refuses whole categories such as .each().
What they do well: navigation, basic interactions, straightforward assertions, and describe/it to test.describe/test restructuring. What they leave for you:
- cy.intercept route matchers, especially the object form and anything with a method filter.
- Custom commands, which are usually left as unresolved references.
- Strict mode violations, which only appear when you run the output.
- Test-id attribute configuration, which no converter can infer.
- Anything inside .then() where the jQuery object model was being used.
Use a converter for the first pass, then budget review time per spec. The output compiles far more often than it is correct.
Running Your Migrated Suite at Scale
Once specs are ported, the constraint moves from framework to infrastructure. Playwright parallelises for free on one machine, but a full cross-browser matrix on real Safari, older Chrome versions and multiple operating systems still needs machines you do not want to maintain.
Running the migrated suite on a cloud grid lets you keep the parallelism Playwright gives you and add the browser coverage that motivated the migration in the first place. See the setup guide for Playwright testing with TestMu AI to point an existing playwright.config.ts at the cloud.
If selector maintenance was part of why you left Cypress, it is worth knowing that it follows you across frameworks. A Playwright alternative that authors flows in natural language and self-heals when the DOM shifts is worth evaluating alongside the migration rather than after it.
How Long Does a Cypress to Playwright Migration Take?
Estimates vary widely because the spec count is the wrong unit. What drives effort is how much shared machinery your suite has.
| Suite profile | Realistic estimate |
|---|---|
| Under 50 specs, few custom commands, single domain | 3 to 5 engineer-days |
| 100 to 200 specs, moderate custom commands and network stubs | 2 to 4 engineer-weeks |
| 500+ specs, heavy custom commands, cy.task, plugin dependencies | 1 to 3 engineer-months, phased |
The first ten specs will take disproportionately long. That is where the config, fixtures, auth setup and page objects get built. After that, straightforward specs land quickly, and the long tail is the specs with custom commands and network stubs.
Treat the table as a floor rather than a forecast. It assumes dedicated time and a suite without heavy plugin dependencies; published accounts from teams running migrations alongside normal delivery work routinely report longer, into several months for large suites. If you are estimating for a roadmap rather than a sprint, plan against the slower end.
Wrapping Up
A Cypress to Playwright migration is less a rewrite than a series of small translations with a handful of genuine redesigns buried in it. Run a converter first, expect strict mode to surface real selector ambiguity, and reserve your actual engineering time for custom commands, network interception and authentication, which is where the work truly is.
Keep both suites running until the new one has earned your trust. The teams that regret migrating are almost always the ones that deleted their Cypress specs too early. If you are still weighing the decision itself, the Cypress vs Playwright comparison lays out the trade-offs, and the Playwright locators guide is the fastest way to get comfortable with the locator model that replaces cy.get.
Author
Ioan Solderea is a software testing and QA leader with 15+ years of experience across test automation, exploratory testing, and QA leadership. He has hands-on expertise in Selenium WebDriver, Cypress, REST Assured, Appium, and CI/CD testing, and currently works as Lead QA at blu BEYOND GmbH. Ioan is a Cypress Ambassador, a former technical writer at Ministry of Testing, and author of multiple publications on modern software testing practices.
Reviewer
Himanshu Sheth is the Director of Marketing (Technical Content) at TestMu AI, with over 8 years of hands-on experience in Selenium, Cypress, and other test automation frameworks. He has authored more than 130 technical blogs for TestMu AI, covering software testing, automation strategy, and CI/CD. At TestMu AI, he leads the technical content efforts across blogs, YouTube, and social media, while closely collaborating with contributors to enhance content quality and product feedback loops. He has done his graduation with a B.E. in Computer Engineering from Mumbai University. Before TestMu AI, Himanshu led engineering teams in embedded software domains at companies like Samsung Research, Motorola, and NXP Semiconductors. He is a core member of DZone and has been a speaker at several unconferences focused on technical writing and software quality.
Cypress to Playwright Migration FAQs
Did you find this page helpful?
More Related Blogs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance
- Advanced access controls
- Advanced data retention rules
- Advanced Local Testing
- Premium Support options
- Early access to beta features
- Private Slack Channel
- Unlimited Manual Accessibility DevTools Tests


















