🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

End to End Testing with Playwright and Cypress

React TestingđŸŸĸ Free Lesson

End to end tests are the most expensive tests you will write and, done well, the only ones that prove the application actually ships: the bundle loads, the router resolves, the API answers, the session cookie persists, and the button the customer came for still works. Most teams arrive at end to end testing with a quieter hope, that it will stand in for the tests they never wrote. It cannot. A suite that drives a real browser takes minutes per run, fails for environmental reasons, and forces you to decide which handful of journeys deserve that budget. This lesson is about that decision: choosing a runner, writing locators and fixtures that do not rot, removing flakiness before it becomes culture, and sharding the run so continuous integration stays inside a coffee break.

💡Spend the budget on journeys, not screens

If a test never fails in a way that would stop a release, it should not be an end to end test. Keep one test per revenue-critical journey and push everything else down the pyramid to component and integration tests where failures are cheap to diagnose.

What this layer is uniquely good at

Unit and component tests deliberately replace the world with fakes, which makes them fast and blind to a specific class of defect: the seams. The build emits the wrong path, the environment variable is absent in production, the API returns a field the frontend renamed, the route guard redirects logged-out users to a page that no longer exists, the cookie is scoped to the wrong subdomain. Every one of those breaks a live user while every mocked test stays green.

End to end coverage is therefore not about breadth. It is about integration seams and user intent. A healthy suite has a small number of long tests for the paths the business depends on, a broad base of fast tests for logic, and no attempt to reach one hundred percent coverage through a browser. The reading order matters too: an end to end test doubles as executable documentation of how sign in, checkout or onboarding is supposed to behave, so write names such as "a returning customer can reorder from history" rather than "test 3".

ConcernPlaywrightCypressSelenium
Browser modelOwn drivers for Chromium, Firefox, WebKitRuns inside the browser under testWebDriver protocol, any driver
WaitingAuto-waits on locators and web-first assertionsCommand queue with explicit assertionsMostly manual explicit waits
ParallelismFirst class with shards and workersParallel via paid dashboard or multiple processesGrid nodes, more setup
Network controlRoute interception, fixtures, HAR replaycy.intercept with time travel debuggingProxy or add-ons
IsolationFresh context per test, storage state reuseSingle tab, test isolation configurableFresh session per test
Best fitMulti-browser coverage at scaleTeams that value a fast feedback loop and debugging UILegacy stacks and existing grids

Playwright has become the default for new React work because browser coverage, parallel sharding and network interception arrive without plugins, and because a fresh browser context per test removes a whole genre of ordering bugs. Cypress remains a good choice when the team wants a visual debug session for every failure and only targets Chromium. Selenium still earns its place where an organisation already runs a grid or the application is not driven by a modern bundler.

Locators that survive a redesign

A selector strategy is a maintenance decision disguised as a syntax preference. Class names are styling hooks and change with every redesign; nth-child breaks the moment a marketing banner is inserted; data attributes written only for tests accumulate until the DOM is half scaffolding. The order that holds up longest is the same order accessibility tools care about: accessible role first, then accessible name, then visible text, and a test id only for elements that genuinely have no name, such as an anonymous icon button.

javascript
// tests/pages/checkout.page.js
export class CheckoutPage {
  constructor(page) {
    this.page = page;
    this.cardField = page.getByLabel(/card number/i);
    this.expiryField = page.getByLabel(/expiry/i);
    this.payButton = page.getByRole('button', { name: /pay now/i });
    this.confirmation = page.getByRole('status');
  }

  async pay({ card = '4242424242424242' } = {}) {
    await this.cardField.fill(card);
    await this.expiryField.fill('12/29');
    await this.payButton.click();
    await this.confirmation.waitFor();
    return this.confirmation.textContent();
  }
}
javascript
// tests/checkout.spec.js
import { test, expect } from '@playwright/test';
import { CheckoutPage } from './pages/checkout.page';

test('a customer can pay with a card', async ({ page }) => {
  await page.goto('/checkout');
  const checkout = new CheckoutPage(page);

  const message = await checkout.pay();
  expect(message).toContain('Payment received');
  await expect(page).toHaveURL(/\/order\/conf-/);
});

Notice what the page object exposes: user goals rather than selectors. A facade with a pay method stays useful when the form gains a field, whereas a class that mirrors every input one for one just moves the churn from the test into the wrapper. Keep page objects thin, and resist putting assertions inside them, because a failure inside a helper explains itself far less clearly than a failure in the test that named the behaviour.

Test data that does not collide

The most common source of red builds is two tests fighting over one account. The second test deletes the cart the first one is asserting on, or the two runs set conflicting feature flags, or a retry half-completes a flow and leaves the account in a state the next run cannot parse. Fix it structurally: every test owns data it created, and setup runs through the API rather than through the UI whenever the API exists.

javascript
// tests/fixtures.js
import { test as base, expect } from '@playwright/test';

export const test = base.extend({
  shopper: async ({ request }, use) => {
    const unique = `${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
    const email = `shopper-${unique}@example.test`;

    const res = await request.post('/api/signup', {
      data: { email, password: 'correct horse battery staple' },
    });
    expect(res.ok()).toBeTruthy();

    await use({ email });
  },
});

export { expect };

Fixtures also buy speed. Creating a session through the user interface costs five or six navigations per test; issuing a token through a seeding endpoint and storing it in a browser context costs one request and skips the login screen entirely. Keep one end to end test that does log in through the UI, so the login flow itself stays covered, and let every other test reuse a prepared session.

Flakiness is a design defect

A test that fails once in ten runs is not a test. It is a random number generator with an opinion, and each retry trains the team to treat red as noise. The causes are almost always structural rather than mysterious: fixed sleeps standing in for conditions, assertions that fire before React has committed, tests sharing mutable state, animations that make screenshot and visibility checks race, and servers whose clocks disagree by a few seconds.

Playwright removes most of the waiting problem by retrying actionability checks and assertions until a deadline passes, so prefer expect(page.locator(...)).toBeVisible over a hand-written delay. Avoid waiting for network idle in single page applications, where a background telemetry beacon keeps the connection open forever. Freeze time only for tests that need it, and disable animation with a reduced motion emulation rather than by guessing how long a transition runs.

Retries belong in the configuration as a safety net for genuinely nondeterministic infrastructure, not as the mechanism that makes a suite pass. Set retries to one in continuous integration, track the flake rate, and quarantine a test that fails twice in a row so it stops blocking merges while someone fixes it. A quarantined test with no owner and no expiry date is just a deleted test with extra steps.

Screenshot baselines and visual review

Assertions about geometry catch what text assertions cannot: a card that overlaps its neighbour, a button whose label clips at two hundred percent zoom, a colour token change that renders white text on a yellow background. Playwright compares full page or element screenshots against baselines and produces a diff image, which makes review a visual act rather than a reading exercise.

Two practices keep the signal clean. Generate baselines in one environment, typically the Linux container continuous integration uses, because font hinting differs between operating systems and will otherwise produce diffs on every developer machine. And set a small pixel threshold plus a maximum diff percentage so anti-aliasing noise does not fail the build, while a shifted layout still does. Review diffs; never accept them blindly, because the reflex of clicking accept is how a regression becomes the new baseline.

javascript
// tests/visual.spec.js
import { test, expect } from '@playwright/test';

test.beforeEach(async ({ page }) => {
  await page.emulateMedia({ reducedMotion: 'reduce' });
  await page.goto('/pricing');
});

test('pricing page matches the approved design', async ({ page }) => {
  await expect(page).toHaveScreenshot('pricing.png', {
    maxDiffPixelRatio: 0.01,
    animations: 'disabled',
  });
});

Sharding the suite so continuous integration stays fast

Speed is a feature of the suite itself. A run that takes twenty minutes gets pushed to nightly, a nightly run gets skipped, and a skipped suite provides exactly as much protection as none. Split the work across runners, upload traces and screenshots only on failure so green runs stay cheap, and give the job a hard timeout so a hung browser cannot consume an hour of billing.

# .github/workflows/e2e.yml
name: e2e
on: [pull_request]

jobs:
  e2e:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    strategy:
      fail-fast: false
      matrix:
        shard: ['1/3', '2/3', '3/3']
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test --shard=${{ matrix.shard }}
        env:
          BASE_URL: https://staging.example.test
      - uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: playwright-report-${{ matrix.shard }}
          path: playwright-report/

Run pull request jobs against a preview deployment rather than the developer's laptop, keep production smoke tests to five or six checks that run after every release, and store the HTML report as an artifact so the first question after a red build, what did the user actually see, has an answer within one click.

Common Mistakes

Writing a browser test for every button so the suite looks comprehensive

Fix: Cover one test per revenue-critical journey here and push everything else to component tests where failures are cheap.

Selecting elements by class name, nth-child or a CSS path

Fix: Query by accessible role and name first, and reserve the test id for elements that have no name at all.

Adding a fixed sleep when a test fails intermittently

Fix: Wait on a condition or a web-first assertion, and treat every sleep as a bug report about a missing synchronization point.

Letting tests share one seeded account

Fix: Give each test its own data through an API fixture, so parallel workers and retries cannot collide.

Retrying until green and accepting screenshot diffs on sight

Fix: Quarantine a test that fails twice, and review every visual diff before it becomes the new baseline.

Best Practices

  • Build a thin page object exposing user goals such as pay or reorder, never a one to one mirror of the form fields
  • Create accounts and sessions through the API, and keep exactly one test that logs in through the user interface
  • Run pull request jobs against a preview deployment with a hard timeout and traces uploaded only on failure
  • Shard across runners and keep fail-fast off, so one flaky shard explains itself instead of cancelling the others
  • Name tests after the business outcome, because the report becomes documentation for anyone triaging a failure at midnight

Key Takeaways

  • This layer exists to catch integration seams and prove journeys, not to maximise coverage numbers
  • Playwright and Cypress differ mainly in browser model, waiting strategy and parallelism; choose by the matrix you must support
  • Locators ordered by role, name and text age far better than class based selectors, and page objects should expose goals rather than fields
  • Flakiness is structural: shared data, arbitrary waits and animation are the usual culprits, and retries only hide them
  • Shard the suite, upload artifacts on failure, and keep the pull request run inside twenty minutes or it will be ignored
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement