पाठ 14 / 25
Component Testing
Mount one component in a real browser.
Testing components without the whole app
Cypress component testing mounts a single component (React, Vue, Angular, Svelte and others, depending on version) in a real browser using your project's dev server, typically Vite or webpack. You choose component testing in the Launchpad, which adds a component block to cypress.config.ts and a support file that registers cy.mount. Tests then use all the usual commands against the mounted component, can pass props and spy on callbacks with cy.stub(). Component tests are faster and more focused than E2E tests and sit between unit and E2E tests. Playwright also offers experimental component testing packages; check the docs for your version.
Mounting a React component
Support file and a spec; the mount import path depends on your framework and Cypress version.
// cypress/support/component.ts
import { mount } from 'cypress/react'; // check the docs for the right import for your setup
declare global {
namespace Cypress {
interface Chainable { mount: typeof mount; }
}
}
Cypress.Commands.add('mount', mount);
// src/components/Counter.cy.tsx
import Counter from './Counter';
describe('<Counter />', () => {
it('increments and reports the new value', () => {
const onChange = cy.stub().as('onChange');
cy.mount(<Counter initial={2} onChange={onChange} />);
cy.contains('button', '+').click();
cy.get('[data-cy=count]').should('have.text', '3');
cy.get('@onChange').should('have.been.calledWith', 3);
});
});Testing an engine on a stand
Component testing bolts the engine to a test stand: you can rev it and measure it precisely without building the whole car around it.
त्वरित जाँच: What does Cypress component testing render?
- A text description of the component
- The full deployed application
- A server-side HTML snapshot only
- A single mounted component in a real browser via the project's dev server
Answer
A single mounted component in a real browser via the project's dev server — Faster and more focused than full E2E flows.