Cypress 21 ๐ฒ Component Testing โ @cypress/react and @cypress/vue
Cypress is best known as an end-to-end testing tool that drives a real browser against a running application. Component testing is the other half of the story: it mounts a single component in isolation, without the router, without the store, without the API server, and asserts on the DOM the component renders. The component is the unit under test, and the browser is the rendering environment. This is the same mental model as React Testing Library or Vue Test Utils, but the assertions run inside the real Cypress runner with its time-travel debugger, its command log, and its automatic retry-ability.
The framework-specific adapters are what make this possible. @cypress/react knows how to mount a React component and how to unmount it between tests, and @cypress/vue does the same for Vue. The adapter is paired with a bundler โ Vite or webpack โ so the component’s imports, styles, and assets resolve exactly the way they do in the application. The result is a component test that looks like a unit test but runs with the fidelity of a browser.
This chapter covers how component testing is set up, how the mount adapters work, how the component’s props, events, and slots are driven from a spec, and how the component test differs from a Cypress end-to-end test. The sections that follow walk through the project setup, the mount API for React and Vue, the interaction and assertion patterns, and the network and styling concerns that come with running in a real browser.
Key point: Cypress component testing mounts a single component in a real browser through a framework adapter (@cypress/react or @cypress/vue) and a bundler (Vite or webpack); the spec drives the component’s props and events and asserts on the rendered DOM, with no application shell, no router, and no server running.
Why component testing exists
The gap between unit tests and end-to-end tests. A unit test with a DOM emulator like jsdom is fast but approximate: layout, CSS, and real browser APIs like ResizeObserver or IntersectionObserver are missing or stubbed. An end-to-end test is faithful but slow and broad: it exercises the whole application to reach one component. Component testing sits between them, mounting one component in a real browser with real CSS and real browser APIs, without the cost of booting the whole application.
The mounting problem. A component rarely renders in isolation in the application โ it receives props from a parent, dispatches events upward, reads from a router or a store, and fetches data. A component test has to supply those dependencies itself. The adapter’s mount function is the seam: it takes the component and the props, renders it into a dedicated mount point, and gives the spec control over everything the component would otherwise inherit from the application.
The adapter and bundler split. React and Vue mount differently, so Cypress ships a separate adapter per framework. The adapter handles the framework’s lifecycle โ creating the root, rendering, unmounting, cleaning up between tests. The bundler handles the module graph: JSX, single-file components, CSS imports, aliases. The two are configured together, and the cypress.config file declares both.
The real-browser trade-off. Component tests are slower than jsdom unit tests because they launch a browser, and they are faster than end-to-end tests because they skip the application. The trade-off is deliberate: the component test buys fidelity โ real layout, real CSS, real browser events โ for the components where the DOM behavior is the thing under test.
The retry-ability advantage. Cypress commands retry their assertions until they pass or time out. A component test that asserts on an asynchronously rendered element does not need an explicit waitFor; the assertion retries. This is the same behavior as the end-to-end runner, applied to a single component.
The isolation discipline. Because the component is mounted alone, the test cannot lean on the application’s global state. Every dependency is explicit in the spec: the props, the stubbed network, the provided store. This discipline is the point โ a component test that passes with explicit dependencies is a component that is genuinely reusable.
a. Project setup and the adapter configuration
Component testing is configured in cypress.config.ts with the component block. The block declares the framework adapter, the bundler, and the spec pattern for component specs.
// cypress.config.ts
import { defineConfig } from "cypress";
export default defineConfig({
component: {
// The bundler that resolves the component's imports
devServer: {
framework: "react", // or "vue"
bundler: "vite", // or "webpack"
},
// Where the component specs live, separate from e2e specs
specPattern: "src/**/*.cy.{ts,tsx,js,jsx}",
},
e2e: {
baseUrl: "http://localhost:3000",
},
});
The devServer block is the pairing of adapter and bundler. The framework value selects the adapter โ @cypress/react for "react", @cypress/vue for "vue" โ and the bundler value selects the build tool that resolves the component’s module graph. The two are installed as dev dependencies and wired together by Cypress, so the spec does not import either adapter directly.
The specPattern for component specs is deliberately separate from the end-to-end specs. The *.cy.tsx suffix is the convention that keeps the two kinds of spec apart, so cypress run --component and cypress run --e2e each pick up their own files.
// src/components/Button.cy.tsx โ a component spec
import Button from "./Button";
describe("Button", () => {
it("renders its label", () => {
// `cy.mount` is the adapter's mount command
cy.mount(<Button label="Save" />);
cy.get("button").should("have.text", "Save");
});
});
The cy.mount command is the adapter’s global command. It is registered by the adapter when the component test runner starts, and the spec calls it without an import. The argument is the component’s element โ JSX for React, a component plus props for Vue โ and the command renders it into the runner’s mount point.
b. The React mount API with @cypress/react
The React adapter’s cy.mount takes a React element and an optional options object. The element is rendered with ReactDOM.createRoot into a container the runner controls, and the container is torn down between tests so each test starts from a clean DOM.
// src/components/Counter.cy.tsx
import Counter from "./Counter";
describe("Counter", () => {
it("increments when clicked", () => {
// Mount the component with its initial props
cy.mount(<Counter initial={0} />);
// Drive the component through the DOM
cy.get("button").contains("+").click();
// Assert on the rendered result
cy.get("[data-testid='count']").should("have.text", "1");
});
});
The spec never imports @cypress/react directly. The adapter registers cy.mount when the runner boots, and the command resolves the React element. The initial prop is supplied by the spec because the component has no parent to supply it, which is the isolation the component test is built on.
Props are re-supplied by re-mounting. The adapter also supports a rerender pattern for the cases where a prop change must be observed without a fresh mount โ the element is passed to cy.mount again and React reconciles the update.
// A prop change observed on the same mounted component
cy.mount(<Greeting name="Alice" />);
cy.get("h1").should("have.text", "Hello, Alice");
// Re-mount with a new prop to observe the render
cy.mount(<Greeting name="Bob" />);
cy.get("h1").should("have.text", "Hello, Bob");
Each cy.mount call is a fresh mount, so the second call is a new component instance. For an in-place prop update, the adapter exposes the React root through the mount return, and the spec calls the root’s render again with the new element.
Context and providers are supplied by wrapping the element in the spec. A component that reads from a theme context or a store gets the provider from the test, not from the application shell.
import { ThemeProvider } from "./ThemeProvider";
import ThemedButton from "./ThemedButton";
it("renders with the dark theme", () => {
// Wrap the component in the provider it depends on
cy.mount(
<ThemeProvider theme="dark">
<ThemedButton label="Save" />
</ThemeProvider>
);
cy.get("button").should("have.css", "background-color", "rgb(20, 20, 20)");
});
The provider is the test’s responsibility, which is the isolation principle in practice. A component that cannot be mounted without the whole application is a component whose dependencies are implicit, and the component test makes that visible.
c. The Vue mount API with @cypress/vue
The Vue adapter’s cy.mount takes the component and an options object with props, slots, and global plugins. The options object is the Vue-specific form of the same seam: the spec supplies everything the component would inherit from the application.
// src/components/Counter.cy.ts
import Counter from "./Counter.vue";
describe("Counter", () => {
it("increments when clicked", () => {
// Mount the SFC with its props
cy.mount(Counter, {
props: { initial: 0 },
});
cy.get("button").contains("+").click();
cy.get("[data-testid='count']").should("have.text", "1");
});
});
The component is the single-file component imported from its .vue file. The props key is the Vue equivalent of React’s element props, and the bundler resolves the SFC’s template, script, and style blocks through the Vue plugin configured for the chosen bundler.
Slots are supplied through the slots key. The slot content is a string or a render function, and the adapter passes it to the component’s named or default slot.
import Card from "./Card.vue";
it("renders the default slot", () => {
cy.mount(Card, {
// The default slot content
slots: {
default: "<p>Card body</p>",
},
});
cy.get(".card").should("contain.text", "Card body");
});
it("renders a named slot", () => {
cy.mount(Card, {
slots: {
header: "<h2>Title</h2>",
},
});
cy.get(".card__header").should("contain.text", "Title");
});
Global plugins โ a router, a Pinia store, an i18n instance โ are supplied through the global key. This is the Vue counterpart to React’s provider wrapping: the spec installs the plugin the component depends on, and nothing else.
import { createPinia } from "pinia";
import { createI18n } from "vue-i18n";
import UserBadge from "./UserBadge.vue";
it("renders the user from the store", () => {
const pinia = createPinia();
const i18n = createI18n({ locale: "en", messages: { en: {} } });
cy.mount(UserBadge, {
// Install the plugins the component reads from
global: { plugins: [pinia, i18n] },
});
cy.get(".badge").should("contain.text", "Alice");
});
Events are asserted through cy.get(...).trigger(...) and through the component’s emitted events. The Vue adapter exposes the emitted events on the mounted wrapper, and the spec asserts on the payload the component emitted, which is the direct test of the component’s contract with its parent.
it("emits update on click", () => {
cy.mount(Counter, { props: { initial: 0 } });
cy.get("button").contains("+").click();
// Assert on the emitted event and its payload
cy.get("@vue").should((wrapper) => {
expect(wrapper.emitted("update")).to.have.length(1);
expect(wrapper.emitted("update")[0]).to.deep.equal([1]);
});
});
Complete Example Session
// ============================================
// PART 1: THE CONFIG
// ============================================
// cypress.config.ts
import { defineConfig } from "cypress";
export default defineConfig({
component: {
devServer: {
framework: "react", // selects @cypress/react
bundler: "vite", // resolves the module graph
},
specPattern: "src/**/*.cy.tsx",
},
});
// ============================================
// PART 2: THE SIMPLE MOUNT
// ============================================
// src/components/Button.cy.tsx
import Button from "./Button";
describe("Button", () => {
it("renders its label", () => {
cy.mount(<Button label="Save" />);
cy.get("button").should("have.text", "Save");
});
});
// ============================================
// PART 3: THE INTERACTION
// ============================================
import Counter from "./Counter";
describe("Counter", () => {
it("increments when clicked", () => {
cy.mount(<Counter initial={0} />);
cy.get("button").contains("+").click();
cy.get("[data-testid='count']").should("have.text", "1");
});
});
// ============================================
// PART 4: THE PROVIDER
// ============================================
import { ThemeProvider } from "./ThemeProvider";
import ThemedButton from "./ThemedButton";
it("renders with the dark theme", () => {
cy.mount(
<ThemeProvider theme="dark">
<ThemedButton label="Save" />
</ThemeProvider>
);
cy.get("button").should("have.css", "background-color", "rgb(20, 20, 20)");
});
// ============================================
// PART 5: THE VUE COMPONENT
// ============================================
// src/components/Counter.cy.ts
import Counter from "./Counter.vue";
describe("Counter", () => {
it("increments when clicked", () => {
cy.mount(Counter, { props: { initial: 0 } });
cy.get("button").contains("+").click();
cy.get("[data-testid='count']").should("have.text", "1");
});
});
// ============================================
// PART 6: THE VUE SLOT
// ============================================
import Card from "./Card.vue";
it("renders the default slot", () => {
cy.mount(Card, { slots: { default: "<p>Card body</p>" } });
cy.get(".card").should("contain.text", "Card body");
});
// ============================================
// PART 7: THE VUE PLUGIN
// ============================================
import { createPinia } from "pinia";
import UserBadge from "./UserBadge.vue";
it("renders the user from the store", () => {
const pinia = createPinia();
cy.mount(UserBadge, { global: { plugins: [pinia] } });
cy.get(".badge").should("contain.text", "Alice");
});
// ============================================
// PART 8: THE EMITTED EVENT
// ============================================
it("emits update on click", () => {
cy.mount(Counter, { props: { initial: 0 } });
cy.get("button").contains("+").click();
cy.get("@vue").should((wrapper) => {
expect(wrapper.emitted("update")[0]).to.deep.equal([1]);
});
});
// ============================================
// PART 9: THE NETWORK STUB
// ============================================
import UserProfile from "./UserProfile";
it("renders the fetched user", () => {
// Stub the network before mounting
cy.intercept("GET", "/api/user/1", { fixture: "user.json" });
cy.mount(<UserProfile userId={1} />);
cy.get("h1").should("have.text", "Alice");
});
// ============================================
// PART 10: THE STYLE ASSERTION
// ============================================
import Alert from "./Alert";
it("renders the danger color", () => {
cy.mount(<Alert kind="danger" message="Failed" />);
cy.get(".alert").should("have.css", "color", "rgb(220, 38, 38)");
});
The ten parts covered the configuration, the simple mount, the interaction, the provider, the Vue component, the Vue slot, the Vue plugin, the emitted event, the network stub, and the style assertion.
Quick Reference
The Mount API
| Framework | Call | Supplies |
|---|---|---|
| React | cy.mount(<Comp prop={x} />) | Element, props, providers |
| React | cy.mount(<Provider><Comp /></Provider>) | Context |
| Vue | cy.mount(Comp, { props }) | Component, props |
| Vue | cy.mount(Comp, { slots }) | Slot content |
| Vue | cy.mount(Comp, { global }) | Plugins, directives |
The Config Block
| Key | Value | Purpose |
|---|---|---|
devServer.framework | "react" / "vue" | Selects the adapter |
devServer.bundler | "vite" / "webpack" | Resolves modules |
specPattern | "src/**/*.cy.tsx" | Component specs |
cypress run --component | flag | Runs component specs |
Assertion Helpers
| Command | Purpose |
|---|---|
cy.get(selector) | Query the mounted DOM |
cy.contains(text) | Query by text |
cy.get(...).click() | Drive a DOM event |
cy.get(...).trigger(...) | Fire a custom event |
cy.get("@vue") | Access the Vue wrapper |
Best Practices
โ Do This:
// Supply props from the spec
cy.mount(<Button label="Save" />); // โ
// Wrap the component in its provider
cy.mount(<ThemeProvider><Button /></ThemeProvider>); // โ
// Stub the network before mounting
cy.intercept("GET", "/api/user", { fixture: "user" }); // โ
// Use the Vue options object
cy.mount(Counter, { props: { initial: 0 } }); // โ
// Assert on the emitted event
expect(wrapper.emitted("update")[0]).to.deep.equal([1]); // โ
โ Don’t Do This:
// Rely on application global state
cy.mount(<Button />); // no props, no provider // โ
// Hit the real API from a component test
cy.mount(<UserProfile userId={1} />); // real fetch // โ
// Mix e2e and component specs
specPattern: "**/*.cy.ts" // both kinds in one pattern // โ
// Assert without retry
expect(cy.get("h1").text()).toBe("Alice"); // not retryable // โ
// Mount the whole app for one component
cy.mount(<App />); // that is an e2e concern // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Mount fails on import | Bundler not configured | Set devServer.bundler |
| Missing CSS | Styles not imported in spec | Import the CSS in the spec |
| Provider error | Context not supplied | Wrap in the provider |
| Flaky network | Real API hit | cy.intercept stub |
| Slot not rendered | slots key missing | Pass the slots option |
| Plugin undefined | global.plugins empty | Install the plugin |
| Wrong spec picked up | Shared specPattern | Separate the patterns |
| No retry on assert | Plain expect on DOM | Use cy.get(...).should |
Real-World Examples
1. React button mount
cy.mount(<Button label="Save" />);
cy.get("button").should("have.text", "Save");
2. React provider wrap
cy.mount(<ThemeProvider theme="dark"><Button /></ThemeProvider>);
3. Vue component mount
cy.mount(Counter, { props: { initial: 0 } });
4. Vue slot
cy.mount(Card, { slots: { default: "<p>Body</p>" } });
5. Vue plugin
cy.mount(UserBadge, { global: { plugins: [pinia] } });
6. Network stub
cy.intercept("GET", "/api/user/1", { fixture: "user.json" });
7. Style assertion
cy.get(".alert").should("have.css", "color", "rgb(220, 38, 38)");
8. Emitted event
expect(wrapper.emitted("update")[0]).to.deep.equal([1]);
9. Vite config
devServer: { framework: "react", bundler: "vite" }
10. Component run
cypress run --component
Visual
The Component Test Stack
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE COMPONENT TEST STACK โ
โ โ
โ spec (*.cy.tsx) โ
โ โ โ
โ โผ โ
โ cy.mount โโโบ adapter (@cypress/react / @cypress/vue) โ
โ โ โ
โ โผ โ
โ bundler (vite / webpack) โโโบ module graph โ
โ โ โ
โ โผ โ
โ real browser โโโบ mounted component โโโบ assertions โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Mount Seam
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ IN THE APPLICATION IN THE COMPONENT TEST โ
โ โ
โ parent supplies props โโโบ spec supplies props โ
โ router provides route โโโบ spec provides router โ
โ store holds state โโโบ spec provides store โ
โ API returns data โโโบ spec stubs the API โ
โ โ
โ mount() is the seam between the two โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Test Pyramid Position
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ END-TO-END slow, whole app, few โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ COMPONENT medium, one component, real browser โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ UNIT (jsdom) fast, one unit, approximate DOM โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Vue Options Object
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cy.mount(Component, { โ
โ props: { initial: 0 }, โ component props โ
โ slots: { default: "..." }, โ slot content โ
โ global: { โ
โ plugins: [pinia, i18n], โ installed plugins โ
โ stubs: { Child: true },โ stubbed children โ
โ }, โ
โ }); โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| React adapter | @cypress/react |
| Vue adapter | @cypress/vue |
| Mount command | cy.mount |
| Config block | component.devServer |
| Bundlers | Vite, webpack |
| Spec suffix | *.cy.tsx / *.cy.ts |
| Run command | cypress run --component |
| Isolation seam | cy.mount arguments |
| Network control | cy.intercept |
| Vue wrapper | cy.get("@vue") |
Key takeaways:
- Component testing mounts one component in a real browser. The adapter handles the framework lifecycle and the bundler resolves the module graph, so the component renders with real CSS and real browser APIs, without the application shell.
- The adapter is selected by framework and the bundler by build tool.
@cypress/reactor@cypress/vueis paired with Vite or webpack in thecomponent.devServerblock, and the spec never imports the adapter directly. - The spec supplies every dependency the component would inherit. Props, providers, plugins, slots, and stubbed network are all explicit in the spec, and that explicitness is the isolation the test is built on.
- React wraps and Vue uses the options object. A React component gets its context from a provider element in the mount call; a Vue component gets its props, slots, and plugins from the second argument to
cy.mount. - Assertions retry through Cypress commands.
cy.get(...).should(...)retries until the assertion passes or times out, so asynchronously rendered elements do not need a manual wait.
Remember: Component testing is the middle rung of the test pyramid โ more faithful than a jsdom unit test and far cheaper than an end-to-end run. The mount adapter is the seam that replaces the application’s parent, router, and store with values the spec controls, and the real browser is what makes the CSS and DOM assertions trustworthy. Keep the component specs separate from the end-to-end specs, stub every network call, and let the isolation discipline show you which components have dependencies they should not have.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!