End-to-End with Playwright

Setup

Example

npm init playwright@latest

Example output

✔ Where to put your end-to-end tests? · e2e
✔ Add a GitHub Actions workflow? (y/N) · true
✔ Install Playwright browsers? (Y/n) · true
✔ Success! Created a Playwright Test project

playwright.config.ts

Start the app automatically before tests:

playwright.config.ts

import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './e2e',
  use: { baseURL: 'http://localhost:3000' },
  webServer: { command: 'npm run build && npm run start', url: 'http://localhost:3000', reuseExistingServer: !process.env.CI },
});

A Purchase Flow Test

// e2e/checkout.spec.ts
import { expect, test } from '@playwright/test';

test('guest can search, add to cart and reach login at checkout', async ({ page }) => {
  await page.goto('/');
  await page.getByRole('searchbox').fill('clean code');
  await page.keyboard.press('Enter');
  await expect(page).toHaveURL(/\/search\?q=clean\+code/);

  await page.getByRole('link', { name: /Clean Code/ }).first().click();
  await page.getByRole('button', { name: 'Add to Cart' }).click();
  await expect(page.getByTestId('cart-count')).toHaveText('1');

  await page.goto('/checkout');
  await expect(page).toHaveURL(/\/login\?next=%2Fcheckout/);
});

Example

npx playwright test

Example output

Running 3 tests using 3 workers
  ✓  1 [chromium] › e2e/checkout.spec.ts:3:5 › guest can search, add to cart and reach login at checkout (2.8s)
  ✓  2 [firefox] › e2e/checkout.spec.ts:3:5 › guest can search, add to cart and reach login at checkout (3.4s)
  ✓  3 [webkit] › e2e/checkout.spec.ts:3:5 › guest can search, add to cart and reach login at checkout (3.1s)

  3 passed (9.6s)