Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 35 ยท Practice and Review

Cheat Sheet

A side-by-side cheat sheet of Cypress and Playwright commands for visiting, finding, acting, asserting, network stubbing, configuration and the CLI.

When you know one tool and need the other, you do not need another tutorial; you need a translation table. This page lines up the everyday Cypress and Playwright commands side by side. Skim it to refresh your memory, or search it with the stand-ins at the end.

Cypress and Playwright cannot run on this site, so all commands below are read-only. The snippets assume a baseUrl is configured, so paths such as /login work, and that Playwright tests are written in TypeScript with import { test, expect } from '@playwright/test'. Defaults and flags change between versions, so check the current documentation of your installed version when something does not behave as listed.

The biggest difference to keep in mind: Cypress commands are queued and chained with no await, while Playwright code is ordinary async code in which every action is awaited. The lessons How Cypress Commands Really Work and Auto-Waiting in Playwright explain why.

flowchart LR
  A["Visit"] --> B["Find"]
  B --> C["Act"]
  C --> D["Assert"]
  D --> E["Network<br/>stub and wait"]
  E --> F["Config and CLI"]

The order of the tables below follows the order you meet things in a test.

Structure of a test

Task Cypress Playwright
Group tests describe('x', () => {}) test.describe('x', () => {})
One test it('does y', () => {}) test('does y', async ({ page }) => {})
Before each test beforeEach(() => {}) test.beforeEach(async ({ page }) => {})
Before all tests before(() => {}) test.beforeAll(async () => {})
After each / all afterEach, after test.afterEach, test.afterAll
Run only this test it.only(...) test.only(...)
Skip a test it.skip(...) test.skip(...)
Reusable step Cypress.Commands.add('login', ...) a fixture with test.extend or a helper function
Reuse a login cy.session('user', () => {...}) storageState file from a setup project
Label a step (log with cy.log('x')) await test.step('x', async () => {})

Visiting and navigating

Task Cypress Playwright
Open a page cy.visit('/login') await page.goto('/login')
Reload cy.reload() await page.reload()
Back / forward cy.go('back'), cy.go('forward') await page.goBack(), await page.goForward()
Check the URL cy.url().should('include', '/home') await expect(page).toHaveURL(/home/)
Check the title cy.title().should('eq', 'Home') await expect(page).toHaveTitle('Home')
Set the viewport cy.viewport(390, 844) await page.setViewportSize({ width: 390, height: 844 })

Finding elements

Task Cypress Playwright
By test id cy.get('[data-cy=save]') page.getByTestId('save') (default attribute data-testid)
By role and name cy.contains('button', 'Save') page.getByRole('button', { name: 'Save' })
By visible text cy.contains('Welcome') page.getByText('Welcome')
By label Testing Library plugin: cy.findByLabelText('Email') page.getByLabel('Email')
By placeholder cy.get('[placeholder="Search"]') page.getByPlaceholder('Search')
By CSS cy.get('.card') page.locator('.card')
Inside an element cy.get('.card').find('button') page.locator('.card').locator('button')
Scope a group of commands cy.get('.card').within(() => {}) chain from a locator: card.getByRole(...)
Filter by text cy.get('li').filter(':contains("Ada")') page.getByRole('listitem').filter({ hasText: 'Ada' })
First / last / nth .first(), .last(), .eq(2) .first(), .last(), .nth(2)
Parent .parent() locator.locator('..')
Count .should('have.length', 3) await expect(loc).toHaveCount(3)

Acting on elements

Task Cypress Playwright
Click .click() await loc.click()
Double / right click .dblclick(), .rightclick() await loc.dblclick(), await loc.click({ button: 'right' })
Type into a field .type('hello') await loc.fill('hello')
Type key by key .type('hello') await loc.pressSequentially('hello')
Clear a field .clear() await loc.clear()
Press a key .type('{enter}') await loc.press('Enter')
Check / uncheck .check(), .uncheck() await loc.check(), await loc.uncheck()
Choose from a select .select('Blue') await loc.selectOption('Blue')
Hover .trigger('mouseover') (no .hover()) await loc.hover()
Focus / blur .focus(), .blur() await loc.focus(), await loc.blur()
Scroll into view .scrollIntoView() await loc.scrollIntoViewIfNeeded()
Upload a file .selectFile('cypress/fixtures/a.pdf') await loc.setInputFiles('a.pdf')
Skip checks (last resort) .click({ force: true }) await loc.click({ force: true })

Asserting

Check Cypress Playwright
Visible .should('be.visible') await expect(loc).toBeVisible()
Not on the page .should('not.exist') await expect(loc).toHaveCount(0)
Exact text .should('have.text', 'Done') await expect(loc).toHaveText('Done')
Contains text .should('contain', 'Do') await expect(loc).toContainText('Do')
Input value .should('have.value', 'x') await expect(loc).toHaveValue('x')
Checked .should('be.checked') await expect(loc).toBeChecked()
Disabled / enabled .should('be.disabled') await expect(loc).toBeDisabled()
Attribute .should('have.attr', 'href', '/a') await expect(loc).toHaveAttribute('href', '/a')
CSS class .should('have.class', 'on') await expect(loc).toHaveClass(/on/)
Negate .should('not.be.visible') await expect(loc).not.toBeVisible()
Several checks chain .and(...) several await expect(...) lines, or expect.soft(...)
Plain value expect(x).to.eq(1) (Chai) expect(x).toBe(1)

Rule of thumb: should in Cypress and expect(locator) in Playwright retry; plain expect(value) on an already-read value does not.

Network

Task Cypress Playwright
Stub a JSON response cy.intercept('GET', '/api/x', { body: [] }) await page.route('**/api/x', r => r.fulfill({ json: [] }))
Stub with a fixture file { fixture: 'x.json' } read the JSON and pass it to fulfill
Force a status { statusCode: 500, body: {} } r.fulfill({ status: 500, json: {} })
Fail the request { forceNetworkError: true } r.abort('failed')
Delay a response { body: [], delay: 2000 } await new Promise(r => setTimeout(r, 2000)) inside the handler
Name a request .as('items') keep the waitForResponse promise
Wait for it cy.wait('@items') await page.waitForResponse('**/api/x')
Inspect the request cy.wait('@items').its('request.body') route.request().postDataJSON()
Send an API call cy.request('POST', '/api/x', body) await request.post('/api/x', { data: body })

Register stubs before the navigation or action that triggers the request. In Playwright, create the waitForResponse promise before the click and await it afterwards.

Configuration

Setting Cypress (cypress.config.js) Playwright (playwright.config.ts)
Base URL e2e: { baseUrl: '...' } use: { baseURL: '...' }
Test folder e2e: { specPattern: '...' } testDir: './tests'
Command / assertion timeout defaultCommandTimeout (4000 ms by default) expect: { timeout } (5000 ms by default)
Whole-test timeout e2e has no direct equivalent per test timeout (30000 ms by default)
Retries retries: { runMode: 2, openMode: 0 } retries: 2
Viewport viewportWidth, viewportHeight use: { viewport: { width, height } }
Video video: true use: { video: 'retain-on-failure' }
Screenshot on failure automatic in cypress run use: { screenshot: 'only-on-failure' }
Trace not available (use the video and the runner) use: { trace: 'on-first-retry' }
Environment variables Cypress.env('KEY'), env in config process.env.KEY
Several browsers --browser flag projects: [{ name: 'chromium' }, ...]

Command line

Task Cypress Playwright
Interactive mode npx cypress open npx playwright test --ui
Run everything, headless npx cypress run npx playwright test
Run one file npx cypress run --spec cypress/e2e/a.cy.js npx playwright test tests/a.spec.ts
Pick a browser --browser chrome --project=chromium
Watch the browser --headed --headed
Filter by title --env grep=login (needs the grep plugin) -g "login"
Debug cy.pause(), .debug() --debug or await page.pause()
Record a test Cypress Studio (experimental) npx playwright codegen http://localhost:3000
Install browsers (Cypress downloads its own binary) npx playwright install
Parallel runs --parallel --record --key ... (Cypress Cloud) --workers=4, and --shard=1/4 across machines
Open the report (see the reporter you configured) npx playwright show-report
Update screenshots (use a visual testing plugin) --update-snapshots

Search the sheet

The stand-in below holds a few rows of the tables as data and lets you search both columns. It is the same idea as a search box on a cheat sheet, and it shows how little code a lookup needs.

JS Search the cheat sheet

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A naive translator

Translating between the tools is mostly a matter of recognizing patterns. The stand-in below does that for six simple Cypress patterns and gives up, honestly, on anything else. It teaches the mapping, but it is not a real converter: real tests have aliases, callbacks and custom commands that need a human.

JS Translate simple Cypress lines to Playwright

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line is not translated on purpose: aliases (.as('me')) and cy.wait('@me') map to a different mechanism in Playwright (a waitForResponse promise or an assertion on the visible result), so a line-by-line rewrite would be wrong.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Playwright call matches cy.get('[data-cy=save]') most closely?

    getByTestId looks up the test-id attribute (data-testid by default). It can be configured to use data-cy as well.
  2. 2. What is the Playwright equivalent of cy.get('input').type('hello') for setting a field's value?

    fill sets the value in one step. Use pressSequentially when the page needs individual key events.
  3. 3. Why do Playwright actions need await while Cypress commands do not?

    Playwright tests are normal async functions. Cypress enqueues commands and runs them after the test body returns.
  4. 4. Where do you register a network stub relative to the action that triggers the request?

    A stub that is registered too late misses the request, so it is registered first in both tools.
  5. 5. How do you run one Playwright test file headed?

    Pass the file path to npx playwright test and add --headed to watch the browser.

Summary

  • Both tools follow the same flow: visit, find, act, assert, with network control and configuration around it.
  • Cypress commands are queued and chained; Playwright code is async and every action is awaited.
  • Prefer role, label and test-id queries, and scope them to the region you mean.
  • should and expect(locator) retry; plain expect(value) does not.
  • Register network stubs before the triggering action; create waitForResponse promises before the click.
  • Check each tool's current docs for flags and defaults before relying on them in CI.

Back to the start: What End-to-End Testing Is