QA Interview
Cypress Component Testing Interview Questions for React (2026)
Practice cypress component testing interview questions react teams ask, with model answers on mounting, stubbing, accessibility, state, and CI strategy.
24 min read | 3,879 words
TL;DR
Strong answers connect Cypress's real-browser component runner to React behavior, controlled dependencies, retryable assertions, and a layered test strategy. Be ready to write a custom mount command, test hooks and context, stub requests, diagnose rerenders, and explain what component tests cannot prove.
Key Takeaways
- Explain component testing as real browser rendering with a controlled application boundary.
- Show a working Cypress React mount setup before discussing advanced abstractions.
- Test observable behavior through accessible queries instead of component internals.
- Control providers, network responses, time, and browser APIs at explicit boundaries.
- Use retryable Cypress assertions and avoid fixed waits or detached element references.
- Balance component coverage with unit, contract, and end-to-end checks based on risk.
- Discuss CI isolation, diagnostics, accessibility limits, and maintainable ownership.
Cypress component testing interview questions react candidates face usually test two abilities at once: can you drive React behavior correctly, and can you choose a useful boundary for the test? A strong answer explains the browser-based component runner, shows real Cypress APIs, and identifies what the test proves and what still needs integration coverage.
Use this hub to rehearse concise answers, then expand them with examples from your own product. The questions progress from setup and mounting through state, network control, accessibility, debugging, architecture, and CI. For a hands-on foundation, review the Cypress component testing guide and its complete component example.
TL;DR
| Topic | What a strong answer covers | Useful API or artifact |
|---|---|---|
| Mounting | Bundler, support file, providers, cleanup | mount() and cy.mount() |
| Selection | User-visible semantics before test IDs | cy.findByRole() with Testing Library or cy.get() |
| React state | Trigger behavior through the DOM | cy.get().click() and retryable should() |
| Dependencies | Control the narrowest meaningful boundary | props, context, cy.intercept(), cy.stub() |
| Async UI | Assert transitions without arbitrary delay | aliases and retryable queries |
| Diagnostics | Preserve command log, screenshots, console errors | Cypress runner and CI artifacts |
| Strategy | Match test layer to risk and fidelity | component, API, contract, end-to-end |
The best interview response states the decision first, gives a concrete implementation, and closes with one limitation or trade-off. The following 50 questions give you enough range for junior, mid-level, and senior interviews.
1. Cypress Component Testing Interview Questions React Fundamentals
Q: What is Cypress Component Testing for React?
Cypress Component Testing mounts one React component into a real browser page managed by Cypress, then drives it with the same command queue and assertions used for browser tests. The boundary is smaller than a deployed application because the test supplies props, providers, and dependencies. It is especially useful for interaction, rendering, CSS, browser APIs, and state transitions that are awkward in a DOM simulation.
Q: How is a component test different from an end-to-end test?
A component test starts at a selected UI boundary and normally replaces routing, backend data, or global application setup. An end-to-end test enters through the deployed product and verifies that independently built layers work together. Component failures are usually faster to localize, while end-to-end failures provide broader integration evidence.
Q: Why use Cypress instead of a headless DOM for React components?
Cypress renders in an actual browser engine, so layout, focus, CSS, native events, and browser APIs behave closer to production. Its interactive runner exposes commands, DOM snapshots, requests, and errors during debugging. The cost is heavier execution and more bundler configuration than a lightweight function or hook test.
Q: What does a component test prove?
It proves that the mounted component behaves as asserted with the supplied props, providers, browser, and controlled dependencies. It does not prove that production routing, authentication, backend deployment, or real service contracts are wired correctly. Name that confidence boundary explicitly instead of calling the test end to end.
Q: Which React components are the best candidates?
Prioritize components with meaningful behavior: forms, validation, conditional panels, keyboard interactions, data states, and reusable business widgets. A purely decorative wrapper may be adequately covered by visual review or a higher-level scenario. Choose cases where isolated control produces clearer evidence than navigating through the whole product.
2. Setup and Cypress Mount Interview Questions
Q: What packages and configuration are required?
Install Cypress and the React adapter that matches the supported React generation, then configure component.devServer for the project's bundler. Vite applications use the Vite framework entry, while webpack applications select webpack. Run npx cypress open --component to let the setup wizard create or confirm the support files, and commit the resulting configuration.
Q: Show a minimal React component test.
The test imports the official React mount helper, mounts a real component, performs a user action, and asserts visible output. This example is internally complete and can run in a configured Cypress component project. The chained assertion retries until React commits the updated state.
import React, { useState } from 'react';
import { mount } from 'cypress/react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button type="button" onClick={() => setCount((value) => value + 1)}>
Count: {count}
</button>
);
}
describe('Counter', () => {
it('increments from a click', () => {
mount(<Counter />);
cy.contains('button', 'Count: 0').click();
cy.contains('button', 'Count: 1').should('be.visible');
});
});
Verify it with npx cypress run --component --spec "src/**/*.cy.tsx". A successful run reports one passing test and no uncaught React error.
Q: Why create a custom cy.mount() command?
A custom command centralizes providers, global styles, router setup, and application defaults without repeating them in every spec. Keep overrides explicit so a test can still exercise a special locale, theme, or store state. Avoid turning the command into an invisible mini-application whose defaults make failures difficult to understand.
Q: How do you type a custom mount command in TypeScript?
Import mount and its option type in the component support file, register the command, and augment Cypress's Chainable interface. The declaration must be visible to the component TypeScript project. Returning mount(component, options) preserves Cypress's chain and mount result.
import React from 'react';
import { mount, type MountOptions, type MountReturn } from 'cypress/react';
declare global {
namespace Cypress {
interface Chainable {
mount(component: React.ReactNode, options?: MountOptions): Chainable<MountReturn>;
}
}
}
Cypress.Commands.add('mount', (component, options = {}) => mount(component, options));
Verify type resolution with npx tsc --noEmit, then run one component spec that calls cy.mount(<Counter />). Do not define the same command in both end-to-end and component support files unless their loaded scopes require it.
Q: How do Vite and webpack affect component tests?
The dev server compiles the component and its imports, so its aliases, JSX transform, CSS pipeline, and environment handling must match the application closely. A mismatch can produce false failures even when the component code is correct. Treat bundler configuration as test infrastructure and keep the chosen Cypress framework and bundler entries aligned with the application.
3. Cypress Component Testing Interview Questions React Rendering and Props
Q: How do you test conditional rendering?
Mount each meaningful state with explicit props rather than mutating component internals. Assert both the required content and the absence of content that would create a dangerous ambiguity. Separate materially different states into named tests so a failure identifies which contract broke.
Q: How do you test callback props?
Pass a Cypress stub as the callback, perform the user action, and assert the call and important arguments. This verifies the component's output contract without implementing a fake parent component. Prefer semantic argument matching over snapshots of large event objects.
function SaveButton({ onSave }: { onSave: (id: string) => void }) {
return <button onClick={() => onSave('draft-42')}>Save draft</button>;
}
it('emits the selected draft id', () => {
const onSave = cy.stub().as('onSave');
cy.mount(<SaveButton onSave={onSave} />);
cy.contains('button', 'Save draft').click();
cy.get('@onSave').should('have.been.calledOnceWith', 'draft-42');
});
Verify this spec with npx cypress run --component --spec "src/SaveButton.cy.tsx". If the callback changes shape, the focused failure shows the exact contract disagreement.
Q: Should you use rerender to test prop changes?
Use the mount result's rerender when the behavior specifically depends on a parent changing props while the same component instance remains relevant. For independent render states, separate mounts are easier to read and isolate. Do not use rerender merely to compress several unrelated assertions into one long test.
Q: How do you verify a component unmounts cleanly?
Exercise the parent behavior that removes the child, then assert the child is absent and any observable cleanup occurred. For a subscription, inject a small dependency whose unsubscribe function can be stubbed and verified. Avoid asserting React lifecycle implementation details when the user-visible outcome already proves the requirement.
Q: How should list rendering be tested?
Supply a small dataset containing the identity and edge cases that matter, such as duplicate labels with unique IDs. Assert item count, accessible names, ordering only when order is contractual, and the action associated with a chosen row. Never depend on React's private key representation because keys are reconciliation metadata, not rendered behavior.
4. State, Hooks, Context, and React Strict Behavior
Q: How do you test local state?
Drive local state through clicks, typing, keyboard input, or another public interaction. Assert the resulting DOM, callback, or browser behavior rather than reading a hook value. This keeps the test valid if state moves from useState to a reducer without changing the component contract.
Q: How do you test a component that consumes context?
Wrap it in the real context provider and pass the smallest representative value required by the scenario. A reusable mount option can select theme, locale, or authenticated identity, but the test should show important non-default values. If provider logic itself is under test, mount the provider with a consumer harness instead of faking the value.
Q: How do you test a custom hook with Cypress Component Testing?
Render a tiny harness component that calls the hook and exposes its observable outputs and actions through accessible HTML. That method keeps hook execution inside React and supports effects that depend on browser APIs. Pure computation inside a hook is usually cheaper to test as a normal unit function after extracting it.
Q: How do you handle React Strict Mode?
Strict Mode can intentionally repeat render and effect setup behavior in development to reveal unsafe side effects. Write effects with correct cleanup and avoid asserting incidental call counts unless the product contract requires them. If a duplicate request appears, investigate effect idempotence before removing Strict Mode from the test wrapper.
Q: Why can a cached DOM element become stale after a rerender?
React may replace a node when keys, branches, or element types change, so a previously yielded raw element can detach. Re-query through Cypress before the next action and let retryability find the current node. Avoid storing DOM nodes in ordinary variables across state transitions.
5. Queries, Actions, Assertions, and Retryability
Q: Which selector strategy should you recommend?
Prefer accessible roles, names, labels, and visible text because they reflect how users and assistive technology find controls. Add stable data-cy attributes when semantic selection is ambiguous or the element has no appropriate user-facing identity. Do not bind tests to generated CSS classes or deep DOM paths that change during harmless refactoring.
Q: Is Testing Library required for Cypress Component Testing?
No, Cypress's built-in cy.get(), cy.contains(), and traversal commands can test components. The Cypress Testing Library plugin adds queries such as findByRole, which can make accessible intent clearer. A team should choose a consistent query policy and understand that semantic queries do not replace an accessibility audit.
Q: Explain Cypress retryability in a React test.
Cypress retries queries and attached assertions until they pass or time out, which fits React's asynchronous commits. An assertion such as cy.contains('Saved').should('be.visible') waits by re-querying rather than sleeping for a guessed duration. Commands with side effects are not blindly replayed, so chain structure still matters.
Q: Why is cy.wait(1000) usually a poor solution?
A fixed delay is longer than necessary on fast runs and may still be too short on slow ones. Wait for an observable condition, a request alias, or a deterministic clock transition instead. Fixed waits hide the actual synchronization contract and increase suite duration without adding confidence.
Q: How do you test keyboard behavior?
Focus the intended control, send supported key sequences with .type() or targeted keyboard events, and assert focus movement or action output. Include semantics such as aria-expanded and accessible names when they are part of the widget contract. Do not assume a mouse click proves keyboard operability.
6. Async Data and Network Control
Q: Can cy.intercept() be used in component tests?
Yes, when the mounted component makes browser network requests, cy.intercept() can spy on or stub those requests. Register the intercept before mounting if an effect fetches immediately. Match method and URL deliberately so an unrelated request cannot satisfy the alias.
Q: Show a loading-to-success network test.
Delay a controlled response just enough to make the loading state observable, alias the route, and then verify the completed UI. The component below uses the browser fetch API, so Cypress can intercept it in the component frame. The response shape and displayed field agree exactly.
import React, { useEffect, useState } from 'react';
function Profile() {
const [name, setName] = useState<string | null>(null);
useEffect(() => {
void fetch('/api/profile').then((response) => response.json()).then((data) => setName(data.name));
}, []);
return name ? <h2>{name}</h2> : <p role="status">Loading profile</p>;
}
it('shows loading and then the profile', () => {
cy.intercept('GET', '/api/profile', {
delay: 50,
statusCode: 200,
body: { name: 'Asha Rao' }
}).as('profile');
cy.mount(<Profile />);
cy.contains('[role="status"]', 'Loading profile').should('be.visible');
cy.wait('@profile').its('response.statusCode').should('eq', 200);
cy.contains('h2', 'Asha Rao').should('be.visible');
});
Verify with npx cypress run --component --spec "src/Profile.cy.tsx". The test should fail meaningfully if the URL, schema, loading indicator, or final heading changes.
Q: How do you test an error response?
Return the exact status and body the component is designed to handle, then assert the recovery message and available next action. A 500, 401, timeout, and malformed success payload represent different contracts and should not be collapsed into one generic error case. Keep at least one service contract check elsewhere because an intercept cannot prove the real backend emits the mocked shape.
Q: When should you inject a client instead of intercepting HTTP?
Inject a client when the component contract is explicitly a repository or service interface and transport behavior is irrelevant. Use intercept when browser request construction, URL, headers, cancellation, or response timing matters. The narrower injected boundary is faster and more precise, while the HTTP boundary gives stronger evidence about frontend networking.
Q: How do you test race conditions between requests?
Control two responses independently and release them in the order that could expose stale data. Trigger the second selection before completing the first, then verify that the latest selection remains authoritative. A credible answer also discusses cancellation through AbortController or request identity checks in the production component.
7. Forms, Time, Browser APIs, and Third Parties
Q: How do you test a controlled React form?
Type through labeled inputs, submit through the visible control, and assert validation, payload callbacks, or the resulting state. Cover one representative valid path plus business-critical boundaries such as empty, trimmed, or malformed values. Avoid setting component state directly because that bypasses event handling and accessibility behavior.
Q: How should debounced input be tested?
Call cy.clock() before mounting so the component's timer is under test control, type the value, and advance time with cy.tick() by the documented debounce interval. Assert that the callback did not fire early and then fired with the final value. Restore behavior automatically through Cypress test isolation rather than sharing a clock across tests.
Q: How do you test window.open or another browser API?
Stub the method on the component frame's window before the user action and assert its arguments. Preserve the browser API boundary instead of changing production code solely for the test. For navigation that Cypress manages specially, verify the intended URL or injected navigation contract rather than forcing a real cross-origin page transition.
Q: How do you test portals such as modals?
Ensure the portal target exists in the component document or let the component create it as production does. Query the rendered dialog by role because it may sit outside the mounted component's immediate container. Verify focus entry, Escape behavior, close action, and focus restoration, not only visible text.
Q: What is the right approach for a third-party component library?
Test your wrapper's configuration and user behavior, not the library's entire implementation. Include interactions where your props, styling, accessibility requirements, or version upgrades create product risk. If a date picker is critical, assert selection and emitted value while leaving the vendor's exhaustive calendar logic to its own suite.
8. Accessibility, Styling, and Visual Confidence
Q: Do role-based queries prove accessibility?
They encourage semantic markup and can expose missing roles or names, but they do not prove keyboard flow, contrast, announcements, zoom behavior, or cognitive usability. Add focused keyboard assertions and an automated accessibility scan where the team supports one. Preserve human evaluation for complex widgets and important journeys.
Q: How do you test focus management in a dialog?
Open the dialog through its real trigger and assert that focus moves to the intended control. Exercise Tab and Escape behavior, close it, and confirm focus returns to the trigger. A visible dialog with lost focus is still a functional defect for keyboard and screen-reader users.
Q: Should component tests assert CSS classes?
Assert classes only when the class itself is a public integration contract, which is uncommon in application code. Prefer visible behavior, computed state, dimensions, or a targeted visual check for styling outcomes. Class-name assertions couple tests to implementation while missing whether the resulting style actually works.
Q: Where does visual testing fit?
Visual comparison can catch layout, typography, icon, and responsive regressions that semantic assertions miss. Stabilize fonts, viewport, animation, data, and time before capturing an image. Use visual checks selectively because baseline review and environment consistency create ongoing maintenance; see the Cypress visual testing guide.
Q: How do you test responsive component behavior?
Set a named viewport before mounting and assert the behavior that changes at the product breakpoint, such as menu disclosure or column collapse. Test a small risk-based set rather than every possible pixel width. Remember that container queries depend on container size, so viewport alone may not establish the required condition.
9. Debugging, Isolation, Performance, and CI
Q: How do you diagnose a test that passes locally but fails in CI?
Compare browser version, viewport, environment values, fonts, CPU pressure, network control, and bundler output before editing waits. Inspect the command log, screenshot, video if enabled, console errors, and request evidence from the failing run. Reproduce with the same headless command and configuration, then fix the missing synchronization or environmental contract.
Q: What causes flaky React component tests?
Common causes include fixed delays, unresolved animation, leaking spies, shared mutable fixtures, ambiguous selectors, uncontrolled requests, and references to nodes replaced by rerenders. Strict Mode can reveal non-idempotent effects but should not be blamed automatically. Classify the actual cause and use the Cypress flaky test guide for a durable correction.
Q: How does test isolation apply to component tests?
Each test should establish its own mount, routes, state, clock, and spies without depending on execution order. Cypress resets browser state around tests according to its isolation behavior, while application singletons can still leak if imported modules retain mutable data. Design production stores and clients so a fresh provider or instance can be created per test.
Q: How do you keep a large component suite fast?
Mount the smallest meaningful boundary, avoid unnecessary real services, remove arbitrary waits, and split specs so CI can distribute them sensibly. Measure duration by test and setup source before optimizing. Do not trade away valuable browser fidelity for a headline runtime target without moving suitable logic to a cheaper unit layer.
Q: What belongs in CI artifacts?
Retain enough evidence to diagnose a failure: screenshots, relevant video policy, console output, reporter results, and safe request details. Redact tokens, personal data, and sensitive fixture content before upload, and apply retention limits. An artifact that cannot be accessed by the owning team is not an effective diagnostic.
10. Architecture and Senior React Testing Strategy
Q: How do component tests fit into a test pyramid or portfolio?
Use unit tests for pure rules and combinations, component tests for rendered behavior with controlled boundaries, contract tests for service compatibility, and end-to-end tests for a small set of integrated journeys. The exact distribution follows risk, architecture, and diagnostic cost rather than a universal percentage. Explain which release decision each layer supports.
Q: Should tests mount leaf components or feature components?
Leaf mounts provide precise feedback for reusable controls, while feature mounts cover collaboration among hooks, providers, and child components. Select the smallest boundary that still includes the behavior and failure mode under discussion. A portfolio normally needs both, with duplication removed when two tests provide the same evidence.
Q: How do you prevent a custom mount helper from becoming too complex?
Keep a small default wrapper and accept typed options for genuinely cross-cutting providers. Put domain-specific builders near their features instead of adding every scenario to one global command. Review hidden defaults regularly because excessive convenience can conceal required state and make specs misleading.
Q: How would you migrate from shallow rendering?
Inventory what each shallow test protects, delete tests tied only to implementation structure, and rewrite valuable behavior against mounted output. Start with representative components that exercise context, effects, forms, and browser behavior. Run old and new coverage briefly where risk requires it, then remove the obsolete authority rather than maintaining two permanent suites.
Q: How do you review a component test in a pull request?
Check that the scenario maps to a user or integration risk, the mount boundary is deliberate, and assertions would fail for the intended regression. Review selectors, network shapes, cleanup, accessibility behavior, and whether a lower layer would be clearer. Also confirm the test title and failure output help a teammate diagnose the issue without opening the implementation first.
11. How Interviewers Grade Your Answers
Interviewers usually grade more than syntax. They listen for a precise test boundary, correct Cypress command behavior, knowledge of React rendering, and awareness of what controlled dependencies cannot prove. A senior answer adds ownership, CI evidence, accessibility, maintainability, and a reason for choosing component testing over another layer.
Use a four-part response under pressure: state the goal, select the boundary, show the mechanism, and name the limitation. For a coding prompt, write imports and real component code, register intercepts before effects fire, and use a retryable assertion. For a design prompt, ask about product risk, bundler, supported browsers, service contracts, and team ownership before proposing a framework.
Practice in the Cypress interview question hub and use the /practice workspace to answer aloud. If you want feedback grounded in your experience, upload your resume through the QAJobFit dashboard and prepare one component-testing story with a concrete defect, decision, and result.
12. Common Mistakes
- Calling every mounted component test a unit test without defining its browser and dependency boundary.
- Mounting the full application for every scenario and recreating a slow end-to-end suite.
- Registering
cy.intercept()after an effect has already sent the request. - Using
cy.wait(1000)instead of waiting for a visible state or aliased request. - Asserting hook variables, private methods, React keys, or component instance details.
- Sharing mutable stores, fixtures, aliases, or spies between tests.
- Selecting generated class names and DOM ancestry when an accessible query exists.
- Treating mocked HTTP data as proof of backend compatibility.
- Ignoring keyboard and focus behavior because mouse clicks pass.
- Disabling Strict Mode to hide unsafe effects without diagnosing them.
- Snapshotting large DOM trees that obscure the behavior the scenario protects.
- Building a global mount command with hidden authentication, data, and provider defaults.
- Uploading screenshots or request logs that contain secrets or personal data.
- Moving all React tests into Cypress even when pure logic belongs in a faster unit suite.
13. Cypress Component Testing Interview Questions React Practice Plan
Rehearse these questions in groups rather than memorizing sentences. First, configure and run the Counter, callback, and Profile examples. Next, explain the boundary and trade-off for forms, context, network errors, focus, and responsive behavior without looking at the answers. Finally, practice a senior design prompt: choose coverage for a checkout feature containing validation, a pricing API, a modal, and a final deployed journey.
Your answer should allocate pure discount rules to unit tests, rendered validation and modal interaction to component tests, pricing compatibility to a contract check, and one critical purchase path to end-to-end coverage. Then add CI diagnostics, data ownership, and accessibility checks. That layered response demonstrates more judgment than simply listing Cypress commands.
Conclusion
Cypress component testing interview questions react teams ask are easiest when you reason from behavior and boundaries. Know how to mount React, provide context, stub callbacks and browser APIs, control requests and time, use retryable assertions, and preserve real-browser evidence.
Do not stop at code. Explain why the component boundary is valuable, what the controlled setup cannot prove, and where contract or end-to-end coverage completes the picture. That combination makes an answer credible for both hands-on SDET work and senior test architecture.
Interview Questions and Answers
What is Cypress Component Testing for React?
It mounts a React component in a real browser controlled by Cypress. The test supplies props and providers, then drives observable behavior with Cypress commands. It offers better browser fidelity and diagnosis than a simulated DOM, while proving less integration than a deployed end-to-end test.
How would you create a reusable React mount command?
I register `cy.mount` around the official `mount` from `cypress/react` and augment the TypeScript `Chainable` interface. The wrapper adds only shared providers and styles, with typed overrides for meaningful variants. Domain-specific setup stays close to its feature.
How do you test a callback prop?
I pass `cy.stub().as('callback')`, perform the user-visible action, and assert the important arguments. This verifies the child-to-parent contract without a fake parent implementation. I avoid matching a complete synthetic event object unless that object is the documented contract.
How do you wait for asynchronous React rendering?
I query the expected state and attach a retryable assertion, or wait on a deliberately aliased request before checking the result. Cypress retries queries until their timeout. I do not add a fixed sleep because it has no relationship to the readiness condition.
How do you test data fetching in a mounted component?
I register `cy.intercept()` before mounting, return a contract-shaped response, and assert loading, success, or recovery behavior. Separate scenarios cover distinct failures such as authorization and server error. A real contract test remains necessary because the stub does not validate the backend.
How do you test context-dependent React components?
I mount the component inside the real provider with a small representative value. Shared context setup can live in a typed mount option, but important non-default state remains visible in the test. If provider behavior is the subject, I include the provider implementation rather than injecting its final value.
What selector strategy do you prefer?
I start with role, accessible name, label, or visible text because those reflect user interaction. I use a stable `data-cy` selector for ambiguous or non-semantic targets. I avoid generated classes and deep CSS paths because they turn refactoring into noise.
How does React Strict Mode affect component tests?
Development Strict Mode may repeat render and effect setup to expose unsafe side effects. I make effects idempotent with correct cleanup and avoid assertions on incidental invocation counts. I investigate duplicate behavior before changing the wrapper.
How do you test a debounced search component?
I call `cy.clock()` before mount, type the query, verify no early callback, and advance the documented interval with `cy.tick()`. Then I assert the final query was emitted once as required. This makes timing deterministic without slowing the suite.
What belongs in component tests versus end-to-end tests?
Component tests cover rendered states, interactions, provider combinations, and controlled failure paths with focused diagnosis. End-to-end tests cover a smaller set of critical deployed integrations and journeys. I place pure combinations lower and service compatibility in contract tests.
How would you debug a CI-only component test failure?
I compare the CI browser, viewport, fonts, environment, bundler output, CPU pressure, and request control with local execution. I inspect screenshots, console errors, command logs, and network evidence from the same headless command. The fix targets the missing condition or environment contract, not an arbitrary longer wait.
How do you keep custom test infrastructure maintainable?
I keep the global mount wrapper thin, typed, and explicit, while feature builders stay with their owners. Native Cypress commands remain visible so documentation and diagnostics retain value. I review defaults, execution time, failure quality, and upgrade compatibility as part of normal platform maintenance.
Frequently Asked Questions
What should I study for a Cypress React component testing interview?
Study mount configuration, props, callbacks, context, hooks, network interception, clock control, accessible selectors, retryability, and CI isolation. Also practice explaining when a component test is preferable to unit or end-to-end coverage.
Is Cypress Component Testing a unit test?
It can exercise a small unit, but it runs rendered React code in a real browser and may include providers, styles, and network behavior. Describe the actual boundary instead of relying on a disputed label.
Can Cypress test React hooks?
Yes, mount a small harness component that invokes the hook and exposes observable behavior. Extract pure calculations for faster direct unit tests when React execution is not part of the risk.
Does cy.intercept work in Cypress component tests?
Yes, it can spy on or stub browser requests made by the mounted component. Register it before mounting when an effect sends the request immediately.
Should I use data-cy selectors in React component tests?
Use accessible roles, names, labels, and visible text when they identify the behavior clearly. Add `data-cy` for stable disambiguation when a semantic selector is unavailable or inappropriate.
How do I avoid flaky Cypress component tests?
Replace fixed waits with retryable assertions or request aliases, control animation and time, isolate stores and fixtures, and re-query after rerenders. Diagnose the cause from runner and CI evidence instead of adding retries blindly.
Are Cypress component tests enough for a React application?
No. They provide strong rendered-component evidence but cannot prove all deployed integrations, real service contracts, or complete user journeys. Combine them with unit, contract, API, accessibility, and selective end-to-end checks.
Related Guides
- Playwright Component Testing Interview Questions for Angular (2026)
- Contract Testing Interview Questions for Microservices (2026)
- Cypress Network Interception Interview Questions for Testers (2026)
- Database Testing Scenario Interview Questions for Senior QA (2026)
- Ecommerce Testing Interview Questions for Senior QA (2026)
- gRPC Testing Interview Questions for QA Engineers (2026)