Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 35 ยท Beyond the Basics

Component Testing

Mount one UI component in a real browser and test it in isolation: Cypress component testing, Playwright experimental component tests, and when to prefer e2e.

An end-to-end test starts the whole application, a database and a browser, then walks through a journey. That is the most realistic test you can write, and also the slowest and the hardest to debug. At the other end, a unit test with a fake DOM is fast, but it cannot tell you whether the component really looks and behaves right in a browser: layout, focus, real events and real CSS are all missing.

Component testing sits in the middle. The test tool builds your front-end code with a dev server, opens a real browser, mounts a single component on an empty page, and lets you drive it with the same commands you use in e2e tests. There is no login, no router, no backend; you give the component its props and check what it renders and which callbacks it calls.

The real tools cannot run on this site, so Cypress and Playwright code here is read-only. The runnable examples are stand-ins: a small mount helper that renders a function component into a text tree and exposes locator-style queries. It shows the idea behind mounting; real tools use a bundler, a real browser and your actual framework.

What mounting means

Both tools follow the same recipe:

  1. A dev server (Vite, webpack or similar) bundles your component and the test file together.
  2. The browser loads a nearly empty host page.
  3. The test calls mount(...), which renders the component into that page with the props and providers (theme, router, store) you give it.
  4. The test finds elements, acts on them, and asserts, using the normal commands of the tool.
flowchart LR
  T["Test file"] --> B["Bundler / dev server"]
  C["Your component"] --> B
  B --> H["Real browser<br/>with empty host page"]
  T -->|"mount(Component, props)"| H
  H --> A["Interact and assert"]

A component test bundles the component with the test, renders it alone in a real browser and drives it like a user.

The same component can be mounted many times with different props, which makes states that are hard to reach in the whole app (empty list, error message, loading) one-line tests.

Cypress component testing

Cypress treats component testing as a second kind of test next to e2e. The config has a component block that names the framework and bundler:

JavaScript
// cypress.config.js (read-only)
import { defineConfig } from 'cypress'

export default defineConfig({
  component: {
    devServer: {
      framework: 'react',   // also: vue, angular, svelte, next, ...
      bundler: 'vite',      // or webpack
    },
  },
})

A support file registers the mount command (the setup wizard generates this for you):

JavaScript
// cypress/support/component.js (read-only)
import { mount } from 'cypress/react'
Cypress.Commands.add('mount', mount)

A spec lives next to the component and uses the same cy.get, cy.contains and should you already know from Your First Cypress Test:

JSX
// Counter.cy.jsx (read-only)
import { Counter } from './Counter'

describe('<Counter />', () => {
  it('starts at the given value and counts up', () => {
    cy.mount(<Counter start={5} />)
    cy.contains('Count: 5').should('be.visible')
    cy.contains('button', 'Add one').click()
    cy.contains('Count: 6').should('be.visible')
  })

  it('reports changes through onChange', () => {
    const onChange = cy.stub().as('onChange')
    cy.mount(<Counter start={0} onChange={onChange} />)
    cy.contains('button', 'Add one').click()
    cy.get('@onChange').should('have.been.calledWith', 1)
  })
})

Open it with npx cypress open --component or run it headless with npx cypress run --component. A callback prop becomes a stub (cy.stub()) so you can assert it was called, which is how component tests check what a component emits.

Playwright component tests

Playwright offers component testing as an experimental feature through packages named like @playwright/experimental-ct-react (there are variants for Vue and Svelte). The word experimental matters: the API and the supported setup can change between releases, so read the current documentation before adopting it for a large project.

You initialize it with the init command's component option, which creates a playwright-ct.config.ts, a playwright/index.html host page and a playwright/index.tsx file where you import global CSS or wrap providers. Tests receive a mount fixture:

TSX
// Counter.spec.tsx (read-only)
import { test, expect } from '@playwright/experimental-ct-react';
import { Counter } from './Counter';

test('counts up', async ({ mount }) => {
  const component = await mount(<Counter start={5} />);

  await expect(component).toContainText('Count: 5');
  await component.getByRole('button', { name: 'Add one' }).click();
  await expect(component).toContainText('Count: 6');
});

test('reports changes through onChange', async ({ mount }) => {
  const calls: number[] = [];
  const component = await mount(
    <Counter start={0} onChange={(value) => calls.push(value)} />
  );
  await component.getByRole('button', { name: 'Add one' }).click();
  expect(calls).toEqual([1]);
});

Run with npx playwright test -c playwright-ct.config.ts. You get the same locators, auto-waiting, traces and parallel workers as in the normal runner (see Locators in Playwright). One limit to remember: the test file runs in Node while the component runs in the browser, so props that are functions or complex objects are passed across a boundary and have some restrictions. The documentation lists what is supported.

A mount helper you can run

The stand-in below builds the core of mount: a component is a function from props and state to a tree; mounting renders it, keeps the state, and re-renders after an event. The returned object has getByText, getByRole and click, which look like the real locator API.

JS A miniature mount helper

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

No output.

Notice what the tests did not need: no server, no router and no login. The same component was mounted three times with different props. That is the main appeal of the technique.

Component tests or end-to-end tests?

They answer different questions, and a healthy suite uses both.

Question Better level
Does the date picker open, allow keyboard selection and call onChange? Component
Does an empty list show the "nothing here yet" message? Component
Does the error banner look right for a long message? Component (plus a screenshot)
Can a visitor register, verify and reach the dashboard? End-to-end
Does the front end work with the real API contract and auth? End-to-end
Is a pure function correct for 40 inputs? Unit

Rules of thumb: use component tests for states and interactions inside one piece of UI, especially states that are expensive to reach through the app. Use end-to-end tests for journeys that cross pages, services and the network. Component tests do not prove that the pieces fit together, so keep a few e2e tests as the safety net. For the unit-level and Testing Library side in React, see Testing React Components, and for choosing a mix see Testing Strategy and the Test Pyramid.

A few cautions apply to both tools. Provide the same providers the real app does (theme, i18n, router) or the component will crash for reasons unrelated to your test. Do not test framework internals such as hook call counts; test what the user sees and what callbacks receive. Stub network calls at the boundary, as shown in Intercepting and Mocking Network Requests.

The second stand-in turns the table above into code: a tiny function that suggests a test level from a few properties of a scenario. It is a thinking aid, not an official rule.

JS Which level should test this?

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a component test do that a jsdom-based unit test cannot?

    Cypress and Playwright component tests mount the component in a real browser, so layout, focus handling and real events are all genuine.
  2. 2. How do you check that a component called its onChange prop in a Cypress component test?

    A stub records calls, so the test can assert it was called with the expected value.
  3. 3. What is true of Playwright component testing?

    The component testing packages carry the experimental label. They use the normal locators, but the setup and API can change.
  4. 4. Which scenario is best covered by an end-to-end test rather than a component test?

    A journey across pages, services and authentication needs the whole system. Component tests cover isolated states and interactions.

Summary

  • Component testing mounts one component in a real browser, with a dev server bundling it, and drives it with the usual commands.
  • Cypress uses a component config block, cy.mount and cy.stub() for callbacks; run with --component.
  • Playwright's component testing is experimental and provides a mount fixture in a separate config.
  • Component tests are great for states and interactions inside one piece of UI; e2e tests protect the journeys across the system.
  • Provide the same providers as the real app and test what users see, not framework internals.

Next: Running Tests in CI