Convert Cypress to Playwright

JavaScript pattern

Migrate from Cypress to Playwright.


Apply with the Grit CLI
grit apply cypress_to_playwright

Converts basic test

BEFORE
describe('A mock test', () => {
  test('works', () => {
    cy.onlyOn(Cypress.env('ENVIRONMENT') === 'local');
    cy.visit('/');
    cy.get('.button').should('exist');
    cy.get('.button').should('contain', 'Hello world');
  });
});
AFTER
import { expect, test } from '@playwright/test';

test.describe('A mock test', () => {
  test('works', async ({ page, request }) => {
    if (process.env.ENVIRONMENT !== 'local') {
      test.skip();
    }
    await page.goto('/');
    await expect(page.locator('.button')).toBeAttached();
    await expect(page.locator('.button')).toContainText('Hello world');
  });
});

Converts requests

BEFORE
cy.request({
  method: 'POST',
  url: '/submit',
  body: JSON.stringify({
    content: 'Hello world',
  }),
  failOnStatusCode: false,
});
cy.contains('Submitted', { timeout: 10000 });
AFTER
import { expect, test } from '@playwright/test';

await request.post('/submit', {
  body: JSON.stringify({
    content: 'Hello world',
  }),
  failOnStatusCode: false,
});
await expect(page.getByText('Submitted')).toBeVisible({ timeout: 10000 });

Converts hooks

BEFORE
describe('Grouping', function () {
  before(function () {
    setup();
  });

  afterEach(function () {
    cy.wait(1000);
    teardown();
  });
});
AFTER
import { expect, test } from '@playwright/test';

test.describe('Grouping', function () {
  test.beforeAll(async function () {
    setup();
  });

  test.afterEach(async function () {
    await page.waitForTimeout(1000);
    teardown();
  });
});

Converts composite queries

BEFORE
describe('Grouping', function () {
  it('my test', async () => {
    cy.get('.header').find('.button').eq(1).click({ force: true });
    cy.get('.sidebar').contains('Files').click();
    cy.get('.header').find('.button').eq(1).should('have.attr', 'disabled');
    cy.get('.button').each((button) => {
      expect(button.text()).to.eql('Submit');
    });
  });
});
AFTER
import { expect, test } from '@playwright/test';

test.describe('Grouping', function () {
  test('my test', async ({ page, request }) => {
    await page.locator('.header').locator('.button').nth(1).click({ force: true });
    await page.locator('.sidebar', { hasText: 'Files' }).click();
    await expect(page.locator('.header').locator('.button').nth(1)).toHaveAttribute('disabled');
    const buttons = await page.locator('.button').all();
    for (const button of buttons) {
      expect(await button.textContent()).toEqual('Submit');
    }
  });
});