Playwright·Cookbook Field Manual
Part 05 · Operations & Advanced Card 28

Component Testing

Card 28: Component Testing

What This Pattern Solves

The suite tests full pages, never a component in isolation. When a component has complex internal state or many edge cases, testing it through the full page is slow and makes root-cause harder. This card demonstrates component-level testing using Playwright’s page-level primitives: inject a component into the running page and interact with it directly.

How It Works

  1. Navigate to any page to get a live DOM root — the page is a vessel, the component is the subject.
  2. Use page.evaluate() to inject the component’s HTML, styles, and event handlers into the DOM.
  3. Query the injected component with standard locators.
  4. Interact and assert on its state.

For teams with framework component testing, replace step 2 with @playwright/experimental-ct-*.

Code Example

await page.evaluate(() => {
  const el = document.createElement('div');
  el.innerHTML = `
    <form data-testid="iso-form">
      <label for="iso-input">Name</label>
      <input id="iso-input" type="text" />
      <button type="submit">Submit</button>
    </form>
    <output data-testid="iso-output"></output>
  `;
  document.body.appendChild(el);
  el.querySelector('form')!.addEventListener('submit', (e) => {
    e.preventDefault();
    const input = el.querySelector('#iso-input') as HTMLInputElement;
    document.querySelector('[data-testid="iso-output"]')!.textContent =
      `Submitted: ${input.value}`;
  });
});

await page.getByLabel('Name').fill('Leia');
await page.getByTestId('iso-submit').click();
await expect(page.getByTestId('iso-output')).toHaveText('Submitted: Leia');

Run This Example

pnpm test src/28-component-testing

Prerequisites

Key Concepts

Live Demo

👇 This component is what the Playwright test interacts with:

Loading…

Run This Example

pnpm test src/28-component-testing