Testing Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How do you decide where to place a test in the pyramid/trophy?
Correct answer: At the lowest level that can still catch the failure
If a bug can be caught by a unit or integration test, a duplicate E2E test only adds cost. E2E is for what lower levels can't see: real wiring, deployment, third-party integrations.
2. Why does Google's “Just Say No to More End-to-End Tests” argue against relying on E2E?
Correct answer: Their failures come late, are hard to isolate and flaky
Good tests are fast, reliable and isolate failures. A suite of mostly E2E tests fails on all three.
3. What is the “testing honeycomb” and where is it used?
Correct answer: A microservices shape: mostly integration tests of each service
Spotify's model fits services whose complexity lies in interactions rather than internal logic.
4. What are Google's “test sizes” (small, medium, large) based on?
Correct answer: The resources a test may use: process, machine or network
Sizes describe constraints that make tests fast and deterministic, independent of the “unit/integration” naming debate.
5. Why are the terms “unit” and “integration” test often ambiguous in discussions?
Correct answer: Teams define the "unit" differently, so agree on levels
Fowler distinguishes sociable vs solitary unit tests; what matters is speed, isolation and confidence, not the label.
6. What is the difference between solitary and sociable unit tests?
Correct answer: Solitary use doubles for all collaborators; sociable use real ones
Sociable tests survive refactoring better; solitary tests localize failures more precisely.
7. What is the classical vs mockist (London school) TDD difference?
Correct answer: Classical verifies state; mockist verifies interactions
Mockist tests couple to the call structure and break on refactoring; classical tests can fail in several places for one bug.
8. What does “don't mock what you don't own” suggest?
Correct answer: Wrap third-party APIs in an adapter, and mock that
A mock of someone else's API encodes your assumptions about it; when the library changes, the mock still passes.
9. Which signal suggests a test suite is too coupled to implementation?
Correct answer: Safe refactors regularly break many tests
Tests should resist refactoring and be sensitive to behaviour changes; these two qualities are a good test of test quality.
10. How do you justify the cost of a new E2E test to the team?
Correct answer: By the flow's business risk and what lower tests miss
Each E2E test adds runtime and maintenance. Tie it to a critical journey and an explicit risk.
11. Where do contract tests fit between a frontend and its API?
Correct answer: They replace part of the slow E2E tests by checking the contract
With Pact, the consumer test produces a contract; the provider verifies it in its pipeline and can block a breaking deploy.
12. What does mutation testing (e.g. Stryker) measure?
Correct answer: Whether tests fail when the code is deliberately changed
It answers what coverage can't: whether the executed code is actually verified. It's expensive, so it's usually run on critical modules.
13. What is property-based testing (e.g. fast-check)?
Correct answer: Checking that a property holds for many generated inputs
Example:
decode(encode(x)) === xfor any string. It finds edge cases people don't think of.14. Why can coverage targets backfire as a KPI?
Correct answer: Teams write tests without real assertions to raise the number
Use coverage to find untested areas and review them, not as a pass/fail goal for people.
15. What is the main value of TDD at a senior level beyond “having tests”?
Correct answer: It drives design toward small, substitutable units
Hard-to-test code is often a design smell: too many responsibilities or hidden dependencies.
16. Which are the main sources of non-determinism in tests, according to Fowler?
Correct answer: Isolation, async behaviour, remote services, time, leaks
For each one there is a fix: isolate data, wait for conditions, replace remote services with doubles, control the clock.
17. A test passes alone but fails when the whole file runs. What is the likely cause?
Correct answer: Shared state leaking between tests in that file
Run with random order (
--sequence.shufflein Vitest,--randomizein Jest) to surface such dependencies early.18. Why are automatic retries in CI dangerous if used without monitoring?
Correct answer: They hide real race conditions users will hit
Track flaky tests (passed on retry) as a metric and treat each one as a bug.
19. How does Playwright sharding work in CI?
npx playwright test --shard=1/4 # ... npx playwright merge-reports ./all-blob-reportsCorrect answer: Each machine runs a part, and reports are merged afterwards
With
fullyParallel: true, sharding is balanced at the test level rather than by files.20. What is the difference between Playwright workers and shards?
Correct answer: Workers are processes on a machine; shards split across machines
Each worker has its own browser; workers are restarted after a failure to keep the environment clean.
21. How should test data be organized for E2E tests that run in parallel against a shared environment?
Correct answer: Each test creates its own unique data, for example via API
Shared records cause collisions when tests run in parallel. Seeding through the API is faster than through the UI.
22. What order of checks makes a CI pipeline give feedback fastest?
Correct answer: Typecheck and lint, then unit tests, then build and E2E
Cheap checks fail fast; slow ones run only when the basics are green or in parallel.
23. Why should a CI test run use
--ci(Jest) or equivalent settings?Correct answer: Missing snapshots fail instead of being written silently
In Vitest, CI is detected automatically: new snapshots aren't written and
.onlyfails the run.24. Why does
vi.mockneed to be hoisted, and what follows from it?Correct answer: Imports run first, so the factory can't use file variables
vi.hoistedlets you create values that are hoisted together with the mock.25. How do you get a fresh copy of a module with module-level state in each test?
beforeEach(() => vi.resetModules()); test("...", async () => { const { counter } = await import("./counter"); });Correct answer: Reset the module registry and import it dynamically
Static imports are evaluated once per file; only a dynamic import after reset gets a new instance.
26. What are the main limitations of jsdom for component tests?
Correct answer: No layout engine, no real navigation, some APIs are missing
Polyfill or mock the missing APIs, or move layout-dependent tests to a real browser (Vitest Browser Mode, Playwright CT).
27. How does happy-dom differ from jsdom?
Correct answer: It's a lighter, faster DOM, but less complete
Both are configured per project or per file via
environment(// @vitest-environment happy-dom).28. What is the trade-off between Vitest pools
threadsandforks?Correct answer: Threads are lighter; forks are more compatible
Vitest uses
forksby default because some libraries break inside worker threads (e.g. segfaults with native addons).29. What does Vitest's
projectsoption (formerly workspace) solve?Correct answer: Running different configs, such as Node and browser, in one run
Each project can have its own environment, setup files and include patterns.
30. What does
expectTypeOfin Vitest test?expectTypeOf(parse("1")).toEqualTypeOf<number>();Correct answer: Types at compile time, useful for generics
Type tests run with
vitest --typecheck(or files*.test-d.ts).31. What is in-source testing in Vitest?
Correct answer: Tests in the same file as the code, removed from production
Handy for small private helpers; the bundler strips the block via
define: { "import.meta.vitest": "undefined" }.32. What is the
testcontext in Vitest and why is it useful for concurrent tests?test.concurrent("a", async ({ expect }) => { expect(await load()).toBe(1); });Correct answer: Each test gets its own; the local
expectkeeps results apartContext can be extended with
test.extend- fixtures, similar to Playwright.33. Why can
jest.useFakeTimers()hang a test that awaits a promise usingsetTimeout?vi.useFakeTimers(); await sleep(1000); // inside: new Promise(r => setTimeout(r, 1000))Correct answer: The timer never fires, as the test is stuck on
awaitStart the promise, then
await vi.advanceTimersByTimeAsync(1000), then await the promise - async variants also flush microtasks.34. What does
act()guarantee in React tests?Correct answer: That updates and effects are flushed before assertions
The test environment must have
IS_REACT_ACT_ENVIRONMENT = true(RTL sets it); otherwise React doesn't warn about missingact.35. How do you test async React Server Components?
Correct answer: Mainly with E2E, as RTL can't render async server components
The Next.js docs recommend E2E testing for async Server Components, since unit tools don't support them yet.
36. How do you unit-test a Next.js Server Action?
Correct answer: Call it as an async function with mocked boundaries
Keep validation and business logic in plain functions; the action stays a thin adapter.
37. How do you test a component inside an error boundary without noisy logs?
Correct answer: Render a throwing child and silence
console.errorthereRestore the spy afterwards so unexpected errors in other tests stay visible.
38. How do you test a component that renders through a portal (modal)?
Correct answer: Query with
screen, which searches all ofdocument.bodyQueries bound to
containermiss portal content;screendoesn't.39. When is it better to test a custom hook via
renderHookrather than through a component?Correct answer: For reusable hooks where the hook itself is the product
For a hook used by one component, testing that component's behaviour gives more confidence with less coupling.
40. How do you test Suspense with data loading in a component test?
Correct answer: Assert the fallback, then
await findBy…the contentThis checks both states the user sees without depending on how data fetching is implemented.
41. Why is mocking
useStateor other React hooks a bad idea?Correct answer: It tests React's internals and breaks on any refactor
Mock boundaries (network, time, browser APIs), not the framework.
42. What are the limits of jest-axe/axe-core checks in jsdom?
Correct answer: Layout rules like contrast can't run, and many issues stay unseen
Combine with browser-based checks (
@axe-core/playwright) and manual keyboard/screen-reader testing.43. How do Playwright fixtures differ from
beforeEachhooks?Correct answer: They're on-demand and composable, with setup and teardown together
Example: a
{ scope: "worker" }fixture creates one account per worker, shared by its tests.44. How do you implement authentication once for the whole suite in Playwright?
projects: [ { name: "setup", testMatch: /auth\.setup\.ts/ }, { name: "chromium", use: { storageState: "playwright/.auth/user.json" }, dependencies: ["setup"] }, ]Correct answer: A setup project logs in and saves
storageStatefor the othersProject dependencies appear in the report and trace, unlike
globalSetup. Keep the auth file out of git.45. What makes visual regression tests (
toHaveScreenshot) flaky, and how do you reduce it?Correct answer: Fonts, OS rendering, animations and dynamic data
Reference images depend on the platform, so generate and compare them in the same environment as CI.
46. What does
page.clockallow in Playwright?Correct answer: Controlling time in the browser, for session expiry tests
Without it, testing a 30-minute timeout means waiting 30 minutes or adding test-only flags to the app.
47. What does
toMatchAriaSnapshotcheck?await expect(page.getByRole("navigation")).toMatchAriaSnapshot(` - navigation: - link "Home" - link "Docs" `);Correct answer: The accessibility tree of a region
It ignores classes and wrappers, so it captures what assistive tech sees.
48. What are the trade-offs of the Page Object Model in Playwright tests?
Correct answer: It removes duplication, but too much abstraction hides intent
Fixtures can provide page objects to tests, keeping setup declarative.
49. What does
expect.softdo?Correct answer: Records the failure but lets the test continue
The test still fails at the end. Useful for checking many independent fields of one page.
50. What does
await expect(async () => { ... }).toPass()do?Correct answer: Retries a whole block until it passes or times out
Useful for eventually-consistent flows, e.g. refreshing until an async job's result appears.
51. How can E2E tests run against recorded API traffic?
Correct answer: With
page.routeFromHAR, replaying a recorded HAR fileIt's a middle ground between full mocks and a live backend, but HAR files go stale with the API.
52. What does
test.stepadd to a Playwright test?Correct answer: Named steps in the report and trace
Steps can be nested and are also handy inside page object methods.
53. Why should E2E tests prefer seeding state via API instead of the UI?
Correct answer: UI setup is slow and fails for unrelated reasons
Playwright's
requestfixture and Cypress'scy.requestmake API setup easy.54. Why can't Cypress commands be mixed with
async/await?Correct answer: Commands are enqueued and return chainables, not promises
Values are obtained with
.then(), aliases (.as()) or assertions with.should().55. Why does this custom check not retry, and how do you fix it?
cy.get(".total").then(($el) => { expect(parseFloat($el.text())).to.be.greaterThan(100); });Correct answer:
.thenruns once; a.shouldcallback retries with the queryThe
.shouldcallback must be free of side effects, since it may run many times.56. What does
cy.origin()solve?Correct answer: Running commands on another origin in one test
Playwright doesn't need it: it controls the browser from outside and works with any origins and tabs.
57. When might Cypress be a better choice than Playwright?
Correct answer: When the team values its time-travel debugging
Playwright wins on multi-browser, multi-tab and multi-language support; both have component testing and CI integrations.
58. What is the difference between a mock and a fake?
Correct answer: A fake is a working simple version; a mock has call expectations
Fakes give realistic behaviour without infrastructure; mocks check interactions. Both are test doubles.
59. When is verifying interactions (that a mock was called) the right assertion?
Correct answer: When the call itself is the outcome, as with an email
For internal collaborators, prefer checking the observable result.
60. Why is dependency injection helpful for testability?
Correct answer: Dependencies can be replaced without module mocking
Passing a
now()function or an API client as a parameter is the simplest form of DI.61. How do MSW handlers help beyond unit tests?
Correct answer: They also mock the API in Storybook and local development
In the browser MSW uses a Service Worker, in Node.js it intercepts the request modules.
62. What is a risk of MSW handlers drifting from the real API?
Correct answer: Tests stay green while the real integration breaks
OpenAPI-based generation or Pact contracts keep mocks honest.
63. How do you mock a class constructor with Vitest/Jest?
vi.mock("./Logger", () => ({ Logger: vi.fn().mockImplementation(() => ({ log: vi.fn() })), }));Correct answer: Mock the module and return a mock constructor
Logger.mock.instances/mock.resultsgive access to the created instances.64. What do Storybook interaction tests add?
Correct answer: A
playfunction turns stories into browser component testsStories document states and are reused as test cases, so the effort isn't duplicated.
65. What is visual testing of components (e.g. with Storybook + Chromatic) good at?
Correct answer: Catching unintended visual changes across components
Functional tests don't notice a broken layout; visual tests do, but need a review workflow.
66. How do you test a feature behind a feature flag?
Correct answer: Inject the flag value and cover both variants
Combinations of flags grow exponentially - test variants independently and clean up old flags.
67. How do you approach testing in a large legacy frontend without tests?
Correct answer: A few E2E smoke tests, then tests around changed code
Broad smoke tests give a safety net quickly; finer tests grow where the code changes.
68. How do you test date/time formatting for different locales and time zones reliably?
Correct answer: Fix the clock, set
TZ=UTCand use explicit localesOtherwise tests pass in one country and fail in CI or on daylight saving changes.
69. What does test-level parallelism require from test code?
Correct answer: No shared mutable state or reliance on order
Parallelism exposes hidden coupling that sequential runs hid.
70. Which approach to test-ids is most maintainable when roles and names aren't enough?
Correct answer: Stable, meaningful
data-testidattributesPlaywright's
testIdAttributeand Testing Library'sconfigure({ testIdAttribute })let you choose the attribute.71. Why might a senior engineer argue against a test suite full of
toMatchSnapshot()for components?Correct answer: They verify "nothing changed", not "it's correct"
Snapshots fit serialized data (API mappers, error messages), not as a replacement for behaviour tests.
72. What is the main risk of testing through
data-testidonly?Correct answer: Tests don't notice accessibility regressions
Role and label queries double as accessibility checks; test ids don't.
73. Which metric best shows the health of a test suite to a team?
Correct answer: Run time, flaky rate, escaped bugs and time to fix
A fast, reliable suite that catches real bugs before release is the goal; coverage is just one input.
74. How can E2E tests catch hydration mismatches and other runtime errors that don't break the visible UI?
const errors: string[] = []; page.on("console", (msg) => msg.type() === "error" && errors.push(msg.text())); page.on("pageerror", (error) => errors.push(error.message)); // ...test steps expect(errors).toEqual([]);Correct answer: Fail tests on
consoleandpageerroreventsReact reports hydration mismatches in the console; without a listener the test passes while the page re-renders on the client.
75. What does
vitest --changed(or Jest--changedSince) give a large repository, and what is its limit?Correct answer: Fast runs of affected tests; a full run is still needed
Affected-test selection relies on the import graph; changes to configs, environment or files loaded at runtime aren't always detected.