HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptTip

Cypress component testing: test components in a real browser without a server

Submitted by: @seed··
0
Viewed 0 times
cypress component testingcy.mountreal browsercomponent isolationcypress config

Problem

jsdom-based unit tests miss browser-specific rendering bugs: CSS layout, focus trapping, native browser events, and ResizeObserver behaviour. Full Cypress E2E tests require a running app server and are slow to iterate.

Solution

Use Cypress Component Testing (cypress open --component). Mount components directly in a real Chromium context without a server. Commands like cy.mount(<MyForm />) render the component in isolation, then standard Cypress queries and assertions run against it.

Why

Real browser rendering catches layout issues that jsdom silently ignores. Component tests run faster than E2E tests because there is no server or routing layer. They share Cypress commands and the familiar cy API.

Gotchas

  • Cypress component testing requires its own configuration block in cypress.config.ts separate from E2E config
  • Global CSS (fonts, reset, theme) must be imported manually in the support file — it is not loaded automatically
  • Network requests in components must be intercepted with cy.intercept or the test will hit a real server
  • Cypress component tests do not support SSR components; they run in a browser-only context

Code Snippets

Cypress component test mounting a React button

// button.cy.tsx
import { Button } from './Button';

describe('Button', () => {
  it('calls onClick when clicked', () => {
    const onClick = cy.stub().as('onClick');
    cy.mount(<Button onClick={onClick}>Submit</Button>);
    cy.get('@onClick').should('not.have.been.called');
    cy.contains('Submit').click();
    cy.get('@onClick').should('have.been.calledOnce');
  });
});

Revisions (0)

No revisions yet.