Cypress v14 Component Testing Skill
You are an expert in Cypress v14 component testing. When the user asks you to set up component testing with Cypress, write component tests for React/Vue/Angular components, configure mount commands, or integrate with Vite or Webpack, follow these detailed instructions.
Core Principles
- Component isolation -- Mount components in isolation with controlled props, slots, and context. Test one component at a time without page-level dependencies.
- Real browser rendering -- Unlike JSDOM-based tests, Cypress component tests render in a real browser. Leverage this for accurate styling, layout, and interaction testing.
- User-centric interactions -- Interact with components the way users do: click buttons, type in inputs, select options. Avoid testing implementation details like state variables.
- Custom mount commands -- Create reusable mount commands that wrap components with required providers (theme, router, store) to avoid boilerplate in every test.
- Visual validation -- Use Cypress's visual capabilities to verify component rendering. Combine interaction tests with visual snapshots for comprehensive coverage.
- Bundler alignment -- Configure Cypress component testing to use the same bundler (Vite or Webpack) as your application for accurate build behavior.
- Accessibility-integrated testing -- Include accessibility checks in component tests using cypress-axe to catch a11y issues at the component level.
Project Structure
src/
components/
Button/
Button.tsx
Button.cy.tsx
Button.module.css
Form/
LoginForm.tsx
LoginForm.cy.tsx
Modal/
Modal.tsx
Modal.cy.tsx
DataTable/
DataTable.tsx
DataTable.cy.tsx
cypress/
support/
component.ts
commands.ts
mount-utils.tsx
fixtures/
test-data.json
cypress.config.ts
Cypress Configuration for Component Testing
// cypress.config.ts
import { defineConfig } from 'cypress';
export default defineConfig({
component: {
devServer: {
framework: 'react',
bundler: 'vite',
},
specPattern: 'src/**/*.cy.{ts,tsx}',
supportFile: 'cypress/support/component.ts',
indexHtmlFile: 'cypress/support/component-index.html',
viewportWidth: 1280,
viewportHeight: 720,
video: false,
screenshotOnRunFailure: true,
},
e2e: {
baseUrl: 'http://localhost:3000',
specPattern: 'cypress/e2e/**/*.cy.{ts,tsx}',
},
});
Custom Mount Commands
// cypress/support/mount-utils.tsx
import React from 'react';
import { mount } from 'cypress/react';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from '../src/providers/theme-provider';
interface MountOptions {
routerProps?: Record<string, any>;
queryClient?: QueryClient;
theme?: 'light' | 'dark';
initialRoute?: string;
}
export function mountWithProviders(
component: React.ReactElement,
options: MountOptions = {}
) {
const queryClient = options.queryClient || new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0 },
},
});
const wrapped = (
<QueryClientProvider client={queryClient}>
<ThemeProvider defaultTheme={options.theme || 'light'}>
<BrowserRouter>
{component}
</BrowserRouter>
</ThemeProvider>
</QueryClientProvider>
);
return mount(wrapped);
}
// Register as custom command
declare global {
namespace Cypress {
interface Chainable {
mountWithProviders(
component: React.ReactElement,
options?: MountOptions
): Cypress.Chainable<any>;
}
}
}
Cypress.Commands.add('mountWithProviders', mountWithProviders);
Component Support File
// cypress/support/component.ts
import './commands';
import './mount-utils';
// Import global styles
import '../../src/index.css';
// Import cypress-axe for accessibility testing
import 'cypress-axe';
// Prevent uncaught exceptions from failing tests
Cypress.on('uncaught:exception', (err) => {
if (err.message.includes('ResizeObserver loop')) return false;
return true;
});
React Component Test Examples
// src/components/Button/Button.cy.tsx
import { Button } from './Button';
describe('Button Component', () => {
it('renders with default props', () => {
cy.mount(<Button>Click me</Button>);
cy.get('button').should('be.visible').and('contain.text', 'Click me');
});
it('renders different variants', () => {
const variants = ['primary', 'secondary', 'outline', 'ghost', 'destructive'] as const;
variants.forEach((variant) => {
cy.mount(<Button variant={variant}>Button</Button>);
cy.get('button').should('have.attr', 'data-variant', variant);
});
});
it('renders different sizes', () => {
cy.mount(<Button size="sm">Small</Button>);
cy.get('button').should('have.class', 'btn-sm');
cy.mount(<Button size="lg">Large</Button>);
cy.get('button').should('have.class', 'btn-lg');
});
it('handles click events', () => {
const
cy.mount(<Button me</Button>);
cy.get('button').click();
cy.get('@clickHandler').should('have.been.calledOnce');
});
it('is disabled when disabled prop is true', () => {
const
cy.mount(<Button disabled
cy.get('button').should('be.disabled');
cy.get('button').click({ force: true });
cy.get('@clickHandler').should('not.have.been.called');
});
it('shows loading state', () => {
cy.mount(<Button loading>Loading</Button>);
cy.get('button').should('be.disabled');
cy.get('[data-testid="spinner"]').should('be.visible');
});
it('renders as a link when asChild is provided', () => {
cy.mount(
<Button asChild>
<a href="/home">Home</a>
</Button>
);
cy.get('a').should('have.attr', 'href', '/home');
});
it('passes accessibility audit', () => {
cy.mount(<Button>Accessible Button</Button>);
cy.injectAxe();
cy.checkA11y('button');
});
});
Form Component Test
// src/components/Form/LoginForm.cy.tsx
import { LoginForm } from './LoginForm';
describe('LoginForm Component', () => {
const defaultProps = {
onSubmit: cy.stub().as('submitHandler'),
onForgotPassword: cy.stub().as('forgotHandler'),
};
beforeEach(() => {
cy.mountWithProviders(<LoginForm {...defaultProps} />);
});
it('renders all form fields', () => {
cy.get('input[name="email"]').should('be.visible');
cy.get('input[name="password"]').should('be.visible');
cy.get('button[type="submit"]').should('be.visible').and('contain.text', 'Sign In');
});
it('submits form with valid data', () => {
cy.get('input[name="email"]').type('user@example.com');
cy.get('input[name="password"]').type('Password123!');
cy.get('button[type="submit"]').click();
cy.get('@submitHandler').should('have.been.calledOnceWith', {
email: 'user@example.com',
password: 'Password123!',
});
});
it('shows validation errors for empty submission', () => {
cy.get('button[type="submit"]').click();
cy.contains('Email is required').should('be.visible');
cy.contains('Password is required').should('be.visible');
cy.get('@submitHandler').should('not.have.been.called');
});
it('validates email format', () => {
cy.get('input[name="email"]').type('not-an-email');
cy.get('input[name="email"]').blur();
cy.contains('Please enter a valid email').should('be.visible');
});
it('validates password minimum length', () => {
cy.get('input[name="password"]').type('short');
cy.get('input[name="password"]').blur();
cy.contains('Password must be at least 8 characters').should('be.visible');
});
it('toggles password visibility', () => {
cy.get('input[name="password"]').type('MyPassword');
cy.get('input[name="password"]').should('have.attr', 'type', 'password');
cy.get('[data-testid="toggle-password"]').click();
cy.get('input[name="password"]').should('have.attr', 'type', 'text');
cy.get('[data-testid="toggle-password"]').click();
cy.get('input[name="password"]').should('have.attr', 'type', 'password');
});
it('handles forgot password link', () => {
cy.contains('Forgot password?').click();
cy.get('@forgotHandler').should('have.been.calledOnce');
});
it('shows loading state during submission', () => {
const slowSubmit = cy.stub().callsFake(() => new Promise((r) => setTimeout(r, 1000)));
cy.mountWithProviders(<LoginForm />);
cy.get('input[name="email"]').type('user@example.com');
cy.get('input[name="password"]').type('Password123!');
cy.get('button[type="submit"]').click();
cy.get('button[type="submit"]').should('be.disabled');
cy.get('[data-testid="spinner"]').should('be.visible');
});
it('passes accessibility audit', () => {
cy.injectAxe();
cy.checkA11y('form');
});
});
Modal Component Test
// src/components/Modal/Modal.cy.tsx
import { Modal } from './Modal';
import { useState } from 'react';
function ModalWrapper(props: Partial<React.ComponentProps<typeof Modal>>) {
const [open, setOpen] = useState(true);
return (
<Modal open={open} => setOpen(false)} {...props}>
<Modal.Title>Test Modal</Modal.Title>
<Modal.Content>Modal content goes here</Modal.Content>
<Modal.Footer>
<button => setOpen(false)}>Close</button>
<button>Confirm</button>
</Modal.Footer>
</Modal>
);
}
describe('Modal Component', () => {
it('renders when open is true', () => {
cy.mount(<ModalWrapper />);
cy.get('[role="dialog"]').should('be.visible');
cy.contains('Test Modal').should('be.visible');
cy.contains('Modal content goes here').should('be.visible');
});
it('closes when close button is clicked', () => {
cy.mount(<ModalWrapper />);
cy.contains('Close').click();
cy.get('[role="dialog"]').should('not.exist');
});
it('closes on Escape key press', () => {
cy.mount(<ModalWrapper />);
cy.get('body').type('{esc}');
cy.get('[role="dialog"]').should('not.exist');
});
it('closes on backdrop click', () => {
cy.mount(<ModalWrapper />);
cy.get('[data-testid="modal-backdrop"]').click({ force: true });
cy.get('[role="dialog"]').should('not.exist');
});
it('traps focus within the modal', () => {
cy.mount(<ModalWrapper />);
cy.get('[role="dialog"]').should('be.visible');
// Tab through focusable elements
cy.get('body').tab();
cy.focused().should('contain.text', 'Close');
cy.get('body').tab();
cy.focused().should('contain.text', 'Confirm');
});
it('renders with custom size', () => {
cy.mount(<ModalWrapper size="lg" />);
cy.get('[role="dialog"]').should('have.class', 'modal-lg');
});
it('passes accessibility audit', () => {
cy.mount(<ModalWrapper />);
cy.injectAxe();
cy.checkA11y('[role="dialog"]');
});
});
DataTable Component Test
// src/components/DataTable/DataTable.cy.tsx
import { DataTable } from './DataTable';
const mockData = [
{ id: 1, name: 'Alice', email: 'alice@test.com', role: 'Admin' },
{ id: 2, name: 'Bob', email: 'bob@test.com', role: 'User' },
{ id: 3, name: 'Charlie', email: 'charlie@test.com', role: 'Editor' },
];
const columns = [
{ key: 'name', header: 'Name', sortable: true },
{ key: 'email', header: 'Email', sortable: true },
{ key: 'role', header: 'Role', sortable: false },
];
describe('DataTable Component', () => {
it('renders all rows and columns', () => {
cy.mount(<DataTable data={mockData} columns={columns} />);
// Check headers
cy.get('th').should('have.length', 3);
cy.get('th').eq(0).should('contain.text', 'Name');
// Check rows
cy.get('tbody tr').should('have.length', 3);
cy.get('tbody tr').first().should('contain.text', 'Alice');
});
it('sorts by column when header is clicked', () => {
cy.mount(<DataTable data={mockData} columns={columns} />);
// Sort by name ascending
cy.contains('th', 'Name').click();
cy.get('tbody tr').first().should('contain.text', 'Alice');
// Sort by name descending
cy.contains('th', 'Name').click();
cy.get('tbody tr').first().should('contain.text', 'Charlie');
});
it('renders empty state when no data', () => {
cy.mount(<DataTable data={[]} columns={columns} />);
cy.contains('No data available').should('be.visible');
});
it('handles row selection', () => {
const
cy.mount(<DataTable data={mockData} columns={columns} selectable />);
cy.get('tbody tr').first().find('input[type="checkbox"]').check();
cy.get('@selectHandler').should('have.been.calledWith', [mockData[0]]);
});
it('supports pagination', () => {
const manyRows = Array.from({ length: 25 }, (_, i) => ({
id: i + 1,
name: `User ${i + 1}`,
email: `user${i + 1}@test.com`,
role: 'User',
}));
cy.mount(<DataTable data={manyRows} columns={columns} pageSize={10} />);
cy.get('tbody tr').should('have.length', 10);
cy.contains('button', 'Next').click();
cy.get('tbody tr').should('have.length', 10);
cy.contains('button', 'Next').click();
cy.get('tbody tr').should('have.length', 5);
});
});
Responsive Component Testing
// src/components/Navigation/Navigation.cy.tsx
import { Navigation } from './Navigation';
describe('Navigation Responsive Behavior', () => {
it('shows full menu on desktop', () => {
cy.viewport(1280, 720);
cy.mountWithProviders(<Navigation />);
cy.get('nav').should('be.visible');
cy.get('[data-testid="desktop-menu"]').should('be.visible');
cy.get('[data-testid="mobile-menu-button"]').should('not.be.visible');
});
it('shows hamburger menu on mobile', () => {
cy.viewport(375, 812);
cy.mountWithProviders(<Navigation />);
cy.get('[data-testid="mobile-menu-button"]').should('be.visible');
cy.get('[data-testid="desktop-menu"]').should('not.be.visible');
});
it('toggles mobile menu on hamburger click', () => {
cy.viewport(375, 812);
cy.mountWithProviders(<Navigation />);
cy.get('[data-testid="mobile-menu-button"]').click();
cy.get('[data-testid="mobile-menu"]').should('be.visible');
cy.get('[data-testid="mobile-menu-button"]').click();
cy.get('[data-testid="mobile-menu"]').should('not.be.visible');
});
it('closes mobile menu on navigation', () => {
cy.viewport(375, 812);
cy.mountWithProviders(<Navigation />);
cy.get('[data-testid="mobile-menu-button"]').click();
cy.get('[data-testid="mobile-menu"]').should('be.visible');
cy.get('[data-testid="mobile-menu"]').contains('Home').click();
cy.get('[data-testid="mobile-menu"]').should('not.be.visible');
});
});
Best Practices
- Colocate component tests with components -- Place
.cy.tsx files next to their component files for easy discovery and maintenance.
- Create custom mount commands with providers -- Wrap components with all necessary providers (router, query client, theme) in a reusable mount command.
- Test interactions, not implementation -- Click buttons, type in fields, and assert on visible output. Do not test React state or internal methods.
- Use cy.stub() for callback props -- Stub event handlers and verify they are called with correct arguments instead of testing side effects.
- Include accessibility checks -- Add
cy.injectAxe() and cy.checkA11y() to component tests for automated accessibility validation.
- Test responsive behavior -- Use
cy.viewport() to test components at different screen sizes within component tests.
- Match your application's bundler -- Configure Cypress to use the same Vite or Webpack configuration as your app for accurate rendering.
- Test edge cases with props -- Test components with empty data, long strings, special characters, and boundary values.
- Use data-testid for test-specific selectors -- When semantic selectors are ambiguous, add data-testid attributes for reliable targeting.
- Keep tests fast -- Component tests should run in milliseconds. Avoid network calls or heavy setup in component tests.
Anti-Patterns
- Testing internal component state -- Accessing React state or calling component methods directly tests implementation, not behavior.
- Mounting entire pages as component tests -- Component testing is for individual components. Use E2E tests for full page flows.
- Not mocking API calls -- Component tests should not make real network requests. Use cy.intercept() to stub API responses.
- Using force: true to bypass visibility checks -- If an element is not visible, the component has a bug. Fix the component, not the test.
- Sharing state between tests -- Each test should mount a fresh component. Do not rely on state from a previous test.
- Testing third-party library behavior -- Do not test that React Router navigates or that a date picker library works. Test your component's behavior.
- Writing overly specific selectors -- Avoid deep CSS selectors like
div > div > button.primary. Use roles, labels, and test IDs.
- Skipping cleanup in test hooks -- Always clean up mocks, stubs, and DOM modifications in afterEach or beforeEach hooks.
- Not testing loading and error states -- Components often have loading spinners and error messages. Test these states explicitly.
- Mounting without required providers -- Components that need context providers will crash without them. Always wrap with necessary providers.
1---2name: cypress-v14-component-testing3description: Component testing patterns with Cypress v14 including React, Vue, and Angular component mounting, custom mount commands, interaction testing, visual snapshots, and integration with Vite and Webpack bundlers.4version: 1.0.05author: thetestingacademy6license: MIT7tags: [cypress, component-testing, react, vue, angular, vite, webpack, mount, visual-testing, interaction-testing]8testingTypes: [unit, integration, visual, accessibility]9frameworks: [cypress]10languages: [typescript, javascript]11domains: [web, frontend]12agents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]13metadata:14 source: https://skillmd.com/skills/pramoddutta/cypress-v14-component-testing15---1617# Cypress v14 Component Testing Skill1819You are an expert in Cypress v14 component testing. When the user asks you to set up component testing with Cypress, write component tests for React/Vue/Angular components, configure mount commands, or integrate with Vite or Webpack, follow these detailed instructions.2021## Core Principles22231. **Component isolation** -- Mount components in isolation with controlled props, slots, and context. Test one component at a time without page-level dependencies.242. **Real browser rendering** -- Unlike JSDOM-based tests, Cypress component tests render in a real browser. Leverage this for accurate styling, layout, and interaction testing.253. **User-centric interactions** -- Interact with components the way users do: click buttons, type in inputs, select options. Avoid testing implementation details like state variables.264. **Custom mount commands** -- Create reusable mount commands that wrap components with required providers (theme, router, store) to avoid boilerplate in every test.275. **Visual validation** -- Use Cypress's visual capabilities to verify component rendering. Combine interaction tests with visual snapshots for comprehensive coverage.286. **Bundler alignment** -- Configure Cypress component testing to use the same bundler (Vite or Webpack) as your application for accurate build behavior.297. **Accessibility-integrated testing** -- Include accessibility checks in component tests using cypress-axe to catch a11y issues at the component level.3031## Project Structure3233```34src/35 components/36 Button/37 Button.tsx38 Button.cy.tsx39 Button.module.css40 Form/41 LoginForm.tsx42 LoginForm.cy.tsx43 Modal/44 Modal.tsx45 Modal.cy.tsx46 DataTable/47 DataTable.tsx48 DataTable.cy.tsx49cypress/50 support/51 component.ts52 commands.ts53 mount-utils.tsx54 fixtures/55 test-data.json56cypress.config.ts57```5859## Cypress Configuration for Component Testing6061```typescript62// cypress.config.ts63import { defineConfig } from 'cypress';6465export default defineConfig({66 component: {67 devServer: {68 framework: 'react',69 bundler: 'vite',70 },71 specPattern: 'src/**/*.cy.{ts,tsx}',72 supportFile: 'cypress/support/component.ts',73 indexHtmlFile: 'cypress/support/component-index.html',74 viewportWidth: 1280,75 viewportHeight: 720,76 video: false,77 screenshotOnRunFailure: true,78 },79 e2e: {80 baseUrl: 'http://localhost:3000',81 specPattern: 'cypress/e2e/**/*.cy.{ts,tsx}',82 },83});84```8586## Custom Mount Commands8788```typescript89// cypress/support/mount-utils.tsx90import React from 'react';91import { mount } from 'cypress/react';92import { BrowserRouter } from 'react-router-dom';93import { QueryClient, QueryClientProvider } from '@tanstack/react-query';94import { ThemeProvider } from '../src/providers/theme-provider';9596interface MountOptions {97 routerProps?: Record<string, any>;98 queryClient?: QueryClient;99 theme?: 'light' | 'dark';100 initialRoute?: string;101}102103export function mountWithProviders(104 component: React.ReactElement,105 options: MountOptions = {}106) {107 const queryClient = options.queryClient || new QueryClient({108 defaultOptions: {109 queries: { retry: false, gcTime: 0 },110 },111 });112113 const wrapped = (114 <QueryClientProvider client={queryClient}>115 <ThemeProvider defaultTheme={options.theme || 'light'}>116 <BrowserRouter>117 {component}118 </BrowserRouter>119 </ThemeProvider>120 </QueryClientProvider>121 );122123 return mount(wrapped);124}125126// Register as custom command127declare global {128 namespace Cypress {129 interface Chainable {130 mountWithProviders(131 component: React.ReactElement,132 options?: MountOptions133 ): Cypress.Chainable<any>;134 }135 }136}137138Cypress.Commands.add('mountWithProviders', mountWithProviders);139```140141## Component Support File142143```typescript144// cypress/support/component.ts145import './commands';146import './mount-utils';147148// Import global styles149import '../../src/index.css';150151// Import cypress-axe for accessibility testing152import 'cypress-axe';153154// Prevent uncaught exceptions from failing tests155Cypress.on('uncaught:exception', (err) => {156 if (err.message.includes('ResizeObserver loop')) return false;157 return true;158});159```160161## React Component Test Examples162163```typescript164// src/components/Button/Button.cy.tsx165import { Button } from './Button';166167describe('Button Component', () => {168 it('renders with default props', () => {169 cy.mount(<Button>Click me</Button>);170 cy.get('button').should('be.visible').and('contain.text', 'Click me');171 });172173 it('renders different variants', () => {174 const variants = ['primary', 'secondary', 'outline', 'ghost', 'destructive'] as const;175176 variants.forEach((variant) => {177 cy.mount(<Button variant={variant}>Button</Button>);178 cy.get('button').should('have.attr', 'data-variant', variant);179 });180 });181182 it('renders different sizes', () => {183 cy.mount(<Button size="sm">Small</Button>);184 cy.get('button').should('have.class', 'btn-sm');185186 cy.mount(<Button size="lg">Large</Button>);187 cy.get('button').should('have.class', 'btn-lg');188 });189190 it('handles click events', () => {191 const onClick = cy.stub().as('clickHandler');192 cy.mount(<Button onClick={onClick}>Click me</Button>);193194 cy.get('button').click();195 cy.get('@clickHandler').should('have.been.calledOnce');196 });197198 it('is disabled when disabled prop is true', () => {199 const onClick = cy.stub().as('clickHandler');200 cy.mount(<Button disabled onClick={onClick}>Disabled</Button>);201202 cy.get('button').should('be.disabled');203 cy.get('button').click({ force: true });204 cy.get('@clickHandler').should('not.have.been.called');205 });206207 it('shows loading state', () => {208 cy.mount(<Button loading>Loading</Button>);209 cy.get('button').should('be.disabled');210 cy.get('[data-testid="spinner"]').should('be.visible');211 });212213 it('renders as a link when asChild is provided', () => {214 cy.mount(215 <Button asChild>216 <a href="/home">Home</a>217 </Button>218 );219 cy.get('a').should('have.attr', 'href', '/home');220 });221222 it('passes accessibility audit', () => {223 cy.mount(<Button>Accessible Button</Button>);224 cy.injectAxe();225 cy.checkA11y('button');226 });227});228```229230## Form Component Test231232```typescript233// src/components/Form/LoginForm.cy.tsx234import { LoginForm } from './LoginForm';235236describe('LoginForm Component', () => {237 const defaultProps = {238 onSubmit: cy.stub().as('submitHandler'),239 onForgotPassword: cy.stub().as('forgotHandler'),240 };241242 beforeEach(() => {243 cy.mountWithProviders(<LoginForm {...defaultProps} />);244 });245246 it('renders all form fields', () => {247 cy.get('input[name="email"]').should('be.visible');248 cy.get('input[name="password"]').should('be.visible');249 cy.get('button[type="submit"]').should('be.visible').and('contain.text', 'Sign In');250 });251252 it('submits form with valid data', () => {253 cy.get('input[name="email"]').type('user@example.com');254 cy.get('input[name="password"]').type('Password123!');255 cy.get('button[type="submit"]').click();256257 cy.get('@submitHandler').should('have.been.calledOnceWith', {258 email: 'user@example.com',259 password: 'Password123!',260 });261 });262263 it('shows validation errors for empty submission', () => {264 cy.get('button[type="submit"]').click();265266 cy.contains('Email is required').should('be.visible');267 cy.contains('Password is required').should('be.visible');268 cy.get('@submitHandler').should('not.have.been.called');269 });270271 it('validates email format', () => {272 cy.get('input[name="email"]').type('not-an-email');273 cy.get('input[name="email"]').blur();274 cy.contains('Please enter a valid email').should('be.visible');275 });276277 it('validates password minimum length', () => {278 cy.get('input[name="password"]').type('short');279 cy.get('input[name="password"]').blur();280 cy.contains('Password must be at least 8 characters').should('be.visible');281 });282283 it('toggles password visibility', () => {284 cy.get('input[name="password"]').type('MyPassword');285 cy.get('input[name="password"]').should('have.attr', 'type', 'password');286287 cy.get('[data-testid="toggle-password"]').click();288 cy.get('input[name="password"]').should('have.attr', 'type', 'text');289290 cy.get('[data-testid="toggle-password"]').click();291 cy.get('input[name="password"]').should('have.attr', 'type', 'password');292 });293294 it('handles forgot password link', () => {295 cy.contains('Forgot password?').click();296 cy.get('@forgotHandler').should('have.been.calledOnce');297 });298299 it('shows loading state during submission', () => {300 const slowSubmit = cy.stub().callsFake(() => new Promise((r) => setTimeout(r, 1000)));301 cy.mountWithProviders(<LoginForm onSubmit={slowSubmit} />);302303 cy.get('input[name="email"]').type('user@example.com');304 cy.get('input[name="password"]').type('Password123!');305 cy.get('button[type="submit"]').click();306307 cy.get('button[type="submit"]').should('be.disabled');308 cy.get('[data-testid="spinner"]').should('be.visible');309 });310311 it('passes accessibility audit', () => {312 cy.injectAxe();313 cy.checkA11y('form');314 });315});316```317318## Modal Component Test319320```typescript321// src/components/Modal/Modal.cy.tsx322import { Modal } from './Modal';323import { useState } from 'react';324325function ModalWrapper(props: Partial<React.ComponentProps<typeof Modal>>) {326 const [open, setOpen] = useState(true);327 return (328 <Modal open={open} onClose={() => setOpen(false)} {...props}>329 <Modal.Title>Test Modal</Modal.Title>330 <Modal.Content>Modal content goes here</Modal.Content>331 <Modal.Footer>332 <button onClick={() => setOpen(false)}>Close</button>333 <button>Confirm</button>334 </Modal.Footer>335 </Modal>336 );337}338339describe('Modal Component', () => {340 it('renders when open is true', () => {341 cy.mount(<ModalWrapper />);342 cy.get('[role="dialog"]').should('be.visible');343 cy.contains('Test Modal').should('be.visible');344 cy.contains('Modal content goes here').should('be.visible');345 });346347 it('closes when close button is clicked', () => {348 cy.mount(<ModalWrapper />);349 cy.contains('Close').click();350 cy.get('[role="dialog"]').should('not.exist');351 });352353 it('closes on Escape key press', () => {354 cy.mount(<ModalWrapper />);355 cy.get('body').type('{esc}');356 cy.get('[role="dialog"]').should('not.exist');357 });358359 it('closes on backdrop click', () => {360 cy.mount(<ModalWrapper />);361 cy.get('[data-testid="modal-backdrop"]').click({ force: true });362 cy.get('[role="dialog"]').should('not.exist');363 });364365 it('traps focus within the modal', () => {366 cy.mount(<ModalWrapper />);367 cy.get('[role="dialog"]').should('be.visible');368369 // Tab through focusable elements370 cy.get('body').tab();371 cy.focused().should('contain.text', 'Close');372 cy.get('body').tab();373 cy.focused().should('contain.text', 'Confirm');374 });375376 it('renders with custom size', () => {377 cy.mount(<ModalWrapper size="lg" />);378 cy.get('[role="dialog"]').should('have.class', 'modal-lg');379 });380381 it('passes accessibility audit', () => {382 cy.mount(<ModalWrapper />);383 cy.injectAxe();384 cy.checkA11y('[role="dialog"]');385 });386});387```388389## DataTable Component Test390391```typescript392// src/components/DataTable/DataTable.cy.tsx393import { DataTable } from './DataTable';394395const mockData = [396 { id: 1, name: 'Alice', email: 'alice@test.com', role: 'Admin' },397 { id: 2, name: 'Bob', email: 'bob@test.com', role: 'User' },398 { id: 3, name: 'Charlie', email: 'charlie@test.com', role: 'Editor' },399];400401const columns = [402 { key: 'name', header: 'Name', sortable: true },403 { key: 'email', header: 'Email', sortable: true },404 { key: 'role', header: 'Role', sortable: false },405];406407describe('DataTable Component', () => {408 it('renders all rows and columns', () => {409 cy.mount(<DataTable data={mockData} columns={columns} />);410411 // Check headers412 cy.get('th').should('have.length', 3);413 cy.get('th').eq(0).should('contain.text', 'Name');414415 // Check rows416 cy.get('tbody tr').should('have.length', 3);417 cy.get('tbody tr').first().should('contain.text', 'Alice');418 });419420 it('sorts by column when header is clicked', () => {421 cy.mount(<DataTable data={mockData} columns={columns} />);422423 // Sort by name ascending424 cy.contains('th', 'Name').click();425 cy.get('tbody tr').first().should('contain.text', 'Alice');426427 // Sort by name descending428 cy.contains('th', 'Name').click();429 cy.get('tbody tr').first().should('contain.text', 'Charlie');430 });431432 it('renders empty state when no data', () => {433 cy.mount(<DataTable data={[]} columns={columns} />);434 cy.contains('No data available').should('be.visible');435 });436437 it('handles row selection', () => {438 const onSelect = cy.stub().as('selectHandler');439 cy.mount(<DataTable data={mockData} columns={columns} selectable onSelectionChange={onSelect} />);440441 cy.get('tbody tr').first().find('input[type="checkbox"]').check();442 cy.get('@selectHandler').should('have.been.calledWith', [mockData[0]]);443 });444445 it('supports pagination', () => {446 const manyRows = Array.from({ length: 25 }, (_, i) => ({447 id: i + 1,448 name: `User ${i + 1}`,449 email: `user${i + 1}@test.com`,450 role: 'User',451 }));452453 cy.mount(<DataTable data={manyRows} columns={columns} pageSize={10} />);454 cy.get('tbody tr').should('have.length', 10);455 cy.contains('button', 'Next').click();456 cy.get('tbody tr').should('have.length', 10);457 cy.contains('button', 'Next').click();458 cy.get('tbody tr').should('have.length', 5);459 });460});461```462463## Responsive Component Testing464465```typescript466// src/components/Navigation/Navigation.cy.tsx467import { Navigation } from './Navigation';468469describe('Navigation Responsive Behavior', () => {470 it('shows full menu on desktop', () => {471 cy.viewport(1280, 720);472 cy.mountWithProviders(<Navigation />);473474 cy.get('nav').should('be.visible');475 cy.get('[data-testid="desktop-menu"]').should('be.visible');476 cy.get('[data-testid="mobile-menu-button"]').should('not.be.visible');477 });478479 it('shows hamburger menu on mobile', () => {480 cy.viewport(375, 812);481 cy.mountWithProviders(<Navigation />);482483 cy.get('[data-testid="mobile-menu-button"]').should('be.visible');484 cy.get('[data-testid="desktop-menu"]').should('not.be.visible');485 });486487 it('toggles mobile menu on hamburger click', () => {488 cy.viewport(375, 812);489 cy.mountWithProviders(<Navigation />);490491 cy.get('[data-testid="mobile-menu-button"]').click();492 cy.get('[data-testid="mobile-menu"]').should('be.visible');493494 cy.get('[data-testid="mobile-menu-button"]').click();495 cy.get('[data-testid="mobile-menu"]').should('not.be.visible');496 });497498 it('closes mobile menu on navigation', () => {499 cy.viewport(375, 812);500 cy.mountWithProviders(<Navigation />);501502 cy.get('[data-testid="mobile-menu-button"]').click();503 cy.get('[data-testid="mobile-menu"]').should('be.visible');504505 cy.get('[data-testid="mobile-menu"]').contains('Home').click();506 cy.get('[data-testid="mobile-menu"]').should('not.be.visible');507 });508});509```510511## Best Practices5125131. **Colocate component tests with components** -- Place `.cy.tsx` files next to their component files for easy discovery and maintenance.5142. **Create custom mount commands with providers** -- Wrap components with all necessary providers (router, query client, theme) in a reusable mount command.5153. **Test interactions, not implementation** -- Click buttons, type in fields, and assert on visible output. Do not test React state or internal methods.5164. **Use cy.stub() for callback props** -- Stub event handlers and verify they are called with correct arguments instead of testing side effects.5175. **Include accessibility checks** -- Add `cy.injectAxe()` and `cy.checkA11y()` to component tests for automated accessibility validation.5186. **Test responsive behavior** -- Use `cy.viewport()` to test components at different screen sizes within component tests.5197. **Match your application's bundler** -- Configure Cypress to use the same Vite or Webpack configuration as your app for accurate rendering.5208. **Test edge cases with props** -- Test components with empty data, long strings, special characters, and boundary values.5219. **Use data-testid for test-specific selectors** -- When semantic selectors are ambiguous, add data-testid attributes for reliable targeting.52210. **Keep tests fast** -- Component tests should run in milliseconds. Avoid network calls or heavy setup in component tests.523524## Anti-Patterns5255261. **Testing internal component state** -- Accessing React state or calling component methods directly tests implementation, not behavior.5272. **Mounting entire pages as component tests** -- Component testing is for individual components. Use E2E tests for full page flows.5283. **Not mocking API calls** -- Component tests should not make real network requests. Use cy.intercept() to stub API responses.5294. **Using force: true to bypass visibility checks** -- If an element is not visible, the component has a bug. Fix the component, not the test.5305. **Sharing state between tests** -- Each test should mount a fresh component. Do not rely on state from a previous test.5316. **Testing third-party library behavior** -- Do not test that React Router navigates or that a date picker library works. Test your component's behavior.5327. **Writing overly specific selectors** -- Avoid deep CSS selectors like `div > div > button.primary`. Use roles, labels, and test IDs.5338. **Skipping cleanup in test hooks** -- Always clean up mocks, stubs, and DOM modifications in afterEach or beforeEach hooks.5349. **Not testing loading and error states** -- Components often have loading spinners and error messages. Test these states explicitly.53510. **Mounting without required providers** -- Components that need context providers will crash without them. Always wrap with necessary providers.