Testing Middle 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. What is the difference between
findBy…andwaitFor?Correct answer:
findBywaits for an element;waitForretries any callbackfindByRole(...)is literallywaitFor(() => getByRole(...)). UsefindByto wait for an element andwaitForfor other assertions.2. What is wrong with this
waitFor?await waitFor(async () => { await user.click(screen.getByRole("button", { name: "Save" })); expect(screen.getByText("Saved")).toBeInTheDocument(); });Correct answer: Side effects inside
waitForrepeat on every retryThe callback may run many times, so it should contain only assertions, ideally a single one.
3. How do you wait for a loading spinner to disappear?
Correct answer:
await waitForElementToBeRemoved(() => screen.queryByRole("progressbar"))The helper requires the element to be present at the start, then waits until the query returns
null.4. What does the warning “An update to Component inside a test was not wrapped in act(...)” usually mean?
Correct answer: State changed after the test stopped waiting
RTL already wraps
renderand events inact. The fix is usually to wait for the final UI state withfindBy/waitFor, not to addactmanually.5. What is wrong with waiting like this?
await waitFor(() => {});Correct answer: An empty callback passes at once, hiding a race
Always wait for something observable: an element, a text, a call.
6. How do you use fake timers together with user-event v14?
vi.useFakeTimers(); const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });Correct answer: Pass
advanceTimers, so its delays move the fake clockWithout it, user-event's
delaywaits on asetTimeoutthat never fires and the test times out.7. How do you test a debounced search input?
Correct answer: Use fake timers, type, then advance by the debounce delay
Fake timers make the test fast and deterministic. Real waits slow the suite and still race.
8. What does
vi.runAllTimers()do differently fromvi.advanceTimersByTime(1000)?Correct answer: It runs all pending timers until none are left
With an endless
setInterval,runAllTimersgives up after a limit of iterations - userunOnlyPendingTimersor advance by time.9. How do you fix the current date in a test?
Correct answer:
vi.useFakeTimers()withvi.setSystemTime(...)Code that shows “today” or computes expiry otherwise fails on certain dates or in other time zones.
10. Why can
vi.mock("./api")be written below the imports and still work?Correct answer: Vitest hoists
vi.mockcalls above the importsjest.mockis hoisted by babel-jest the same way.11. Why does this mock factory fail?
const user = { name: "Ann" }; vi.mock("./api", () => ({ getUser: () => user }));Correct answer: The hoisted factory runs before
useris initializedconst user = vi.hoisted(() => ({ name: "Ann" }))is hoisted together with the mock. Jest allows only variables prefixed withmock.12. How do you mock only one export of a module and keep the rest real?
vi.mock("./utils", async (importOriginal) => ({ ...(await importOriginal()), now: () => 0, }));Correct answer: Spread the original module and override one export
Partial mocks keep tests closer to reality: only the inconvenient piece is replaced.
13. What is the difference between
mockClear,mockResetandmockRestore?Correct answer: Clear wipes calls; reset also the implementation; restore the original
Config options
clearMocks,mockResetandrestoreMocksapply them automatically before each test.14. What does
mockImplementationOnceallow?fetchUser .mockRejectedValueOnce(new Error("timeout")) .mockResolvedValueOnce({ name: "Ann" });Correct answer: Different results for consecutive calls
After the “once” values run out, the default implementation (if any) is used.
15. Where do manual mocks for a node module live in Jest?
Correct answer: In a
__mocks__folder next tonode_modulesNode module mocks in root
__mocks__are applied automatically; mocks for your own modules need an explicitjest.mock(path).16. Why does
vi.spyOn(module, "fn")often fail to affect calls inside the same ES module?Correct answer: Internal calls use the local binding, not the export
Mock the module with
vi.mockor move the dependency to another module / inject it.17. Why is MSW often preferred over mocking
fetch/axiosdirectly?Correct answer: Tests don't depend on the HTTP client, and real request code runs
Switching from
axiostofetchdoesn't break tests that mock at the network level.18. How do you set up MSW for tests in Node.js?
const server = setupServer(...handlers); beforeAll(() => server.listen({ onUnhandledRequest: "error" })); afterEach(() => server.resetHandlers()); afterAll(() => server.close());Correct answer: Start once, reset handlers after each test, close at the end
onUnhandledRequest: "error"fails the test on any request without a handler, so nothing reaches a real network.19. How do you make one test get a 500 error from an endpoint with MSW?
server.use( http.get("/api/user", () => new HttpResponse(null, { status: 500 })), );Correct answer: Add a
server.useoverride inside that testRuntime handlers take priority over the initial ones - a neat way to test error states.
20. How do you check what a component sent to the API when using MSW?
Correct answer: Assert on the UI, or capture the body in the handler
Prefer user-visible outcomes; check the payload only when it matters (e.g. the exact data sent to save).
21. How do you render a component that needs providers (router, store, query client)?
function renderWithProviders(ui: ReactElement) { return render(ui, { wrapper: AppProviders }); }Correct answer: Create a custom render with the
wrapperoptionTesting Library docs recommend re-exporting a custom
renderfrom a test utils module.22. How do you search inside one part of the page, e.g. one table row?
const row = screen.getByRole("row", { name: /Ann/ }); within(row).getByRole("button", { name: "Delete" });Correct answer: With
within(element), which scopes the queriesIndex-based queries break when the order changes;
withinkeeps the test meaningful.23. What does
renderHookreturn?const { result } = renderHook(() => useCounter()); act(() => result.current.increment()); expect(result.current.count).toBe(1);Correct answer: An object whose
result.currentholds the latest valueUpdates from outside React events must be wrapped in
act. For hooks used by one component, testing that component is often better.24. How do you test that a component reacts to new props?
Correct answer: Call
rerender(<Comp value="new" />)returned byrenderrerenderupdates the same tree, so state and effects behave like in the app.25. How do you find a heading of a specific level?
Correct answer:
screen.getByRole("heading", { level: 2, name: "Settings" })ByRolesupports options likelevel,checked,pressed,expanded,selected- they check ARIA state too.26. Why can
getByRolemiss an element that is in the DOM?Correct answer: It ignores elements hidden from the accessibility tree
This is usually what you want: hidden elements aren't available to the user either.
27. How do you test a component that reads from a Redux store?
Correct answer: Render it with a real store and assert on the UI
Redux docs recommend integration tests with a real store: they check reducers, selectors and components together.
28. How do you test a component that uses TanStack Query?
Correct answer: Use a fresh
QueryClientper test and MSW for the networkA shared client leaks cache between tests; retries make error tests slow.
29. How do you test a component that depends on the current route (React Router)?
Correct answer: Render it in a
MemoryRouterwithinitialEntriesA memory router gives a real navigation context without a browser URL.
30. How do you check that a checkbox is checked?
Correct answer:
expect(screen.getByRole("checkbox", { name: "Agree" })).toBeChecked()The
checkedattribute reflects only the initial state;toBeCheckedchecks the current state and also works witharia-checked.31. What does
toHaveAccessibleNamecheck?Correct answer: The name that assistive technologies announce
Useful for icon buttons:
<button aria-label="Close">×</button>must be announced as “Close”.32. How can you find the best query for an element quickly?
Correct answer:
screen.logTestingPlaygroundURL()orlogRoles(container)logRolesprints all roles in the tree with their accessible names.33. What is wrong with calling
cleanupmanually inafterEach?Correct answer: It's unnecessary: RTL does it automatically
Manual cleanup is only needed when globals are disabled (Vitest
globals: false) - then register it in setup once.34. Why is
getByRoleslower thangetByText, and what to do about it?Correct answer: It computes the accessibility tree; scope it with
withinIn most suites the difference is negligible, and the confidence gained is worth it.
35. What are the downsides of large component snapshots?
Correct answer: They break easily and get updated without being read
Prefer explicit assertions; use small or inline snapshots (
toMatchInlineSnapshot) for serialized data.36. What is
toMatchInlineSnapshot?Correct answer: A snapshot written directly into the test file
Good for small values: the reviewer sees the expected output without opening
.snapfiles.37. What does branch coverage measure that line coverage misses?
const fee = isVip ? 0 : 10;Correct answer: Whether both outcomes of each condition ran
Branch coverage is a stricter signal for logic-heavy code.
38. What does a coverage threshold in config do?
coverage: { thresholds: { lines: 80, branches: 70 } }Correct answer: Fails the test run if coverage drops too low
Thresholds prevent coverage from silently going down; they shouldn't become a goal by themselves.
39. Which coverage providers does Vitest support?
Correct answer:
v8(default) andistanbulV8 uses the engine's native coverage without instrumentation; Istanbul instruments code.
lcovis a report format.40. What is a setup file (
setupFilesin Vitest,setupFilesAfterEnvin Jest) used for?Correct answer: Shared setup, such as matchers, MSW and polyfills
Jest's
setupFilesAfterEnvruns after the test framework is installed, soexpect.extendand hooks likeafterEachare available there.41. What does
globals: truein Vitest config do?Correct answer: Makes
describe,it,expectandviavailable without importsWithout it you import them from
vitestexplicitly; addvitest/globalsto TStypeswhen enabling it.42. Why do Jest and Vitest isolate test files by default?
Correct answer: So that state from one file doesn't leak into another
Inside one file, state is shared between tests - reset it in hooks.
43. What is a Playwright locator?
Correct answer: A lazy description of an element, resolved on each action
Unlike
ElementHandle, a locator is re-evaluated each time - re-renders don't break it.44. What does strictness mean for Playwright locators?
Correct answer: An action fails if it matches several elements
Narrow the locator (
filter, chaining,name) or use.first()deliberately.45. How do you narrow a list item locator to the one that contains a text?
page.getByRole("listitem").filter({ hasText: "Product 2" }).getByRole("button", { name: "Add" });Correct answer: With
filter({ hasText })and chainingfilteralso supportshas,hasNotandhasNotText.46. Why is
expect(await locator.isVisible()).toBe(true)worse thanawait expect(locator).toBeVisible()?Correct answer: The first checks once; web-first assertions retry
Manual checks on async UI are a common source of flaky tests.
47. How do you mock an API response in Playwright?
await page.route("**/api/products", (route) => route.fulfill({ json: [{ id: 1, name: "Cup" }] }), );Correct answer: With
page.routeandroute.fulfillroute.continue()lets the request through (optionally modified),route.abort()simulates a network failure.48. How do you avoid logging in through the UI in every Playwright test?
Correct answer: Log in once in a setup project and reuse
storageStateThe saved cookies and localStorage are loaded into each new browser context.
49. How does Playwright isolate tests from each other?
Correct answer: Each test gets a new browser context, like a fresh profile
Contexts are cheap to create, so isolation doesn't cost much time.
50. What is the Playwright trace viewer useful for?
Correct answer: Investigating failed CI tests action by action
A common config:
trace: "on-first-retry"- traces only for tests that failed once.51. What are Playwright fixtures?
test("shows profile", async ({ page, context }) => { /* ... */ });Correct answer: Objects passed to tests, set up and torn down automatically
Custom fixtures via
test.extendshare setup (logged-in page, page objects) withoutbeforeEachboilerplate.52. How do you start the app automatically before Playwright tests?
Correct answer: Configure
webServerinplaywright.configreuseExistingServer: !process.env.CIuses a running dev server locally and starts a fresh one in CI.53. What does
expect.polldo in Playwright?await expect.poll(async () => (await api.getOrder(id)).status).toBe("paid");Correct answer: Retries any async function until the value matches
Web-first assertions cover locators;
expect.pollcovers non-UI values.54. Why is
page.waitForTimeout(3000)discouraged?Correct answer: It's slow on fast apps and fails on slower ones
Playwright docs say it should only be used for debugging.
55. What does
test.describe.configure({ mode: "serial" })mean, and why use it rarely?Correct answer: Tests run in order, the rest are skipped after a failure
Independent tests are easier to parallelize and debug.
56. Why can't you write
const text = cy.get("h1").text()in Cypress?Correct answer: Commands are enqueued and don't return values
Commands are chained and executed asynchronously by Cypress; they are not promises and can't be
awaited.57. What gets retried in a Cypress chain like
cy.get(".list li").should("have.length", 3)?Correct answer: The query together with the assertion
Queries and assertions retry; actions like
clickdon't. Avoid long chains of actions between queries.58. How do you wait for a specific request in Cypress?
cy.intercept("POST", "/api/orders").as("createOrder"); cy.contains("Pay").click(); cy.wait("@createOrder").its("response.statusCode").should("eq", 201);Correct answer: Intercept with an alias and
cy.wait("@alias")Waiting on an alias is deterministic; fixed waits are an anti-pattern.
59. What does
cy.session()do?Correct answer: Caches and restores cookies and storage after login
Combined with programmatic login via API (
cy.request), it makes suites much faster.60. What is a key architectural difference between Cypress and Playwright?
Correct answer: Cypress runs in the browser; Playwright drives it from Node.js
Because of this, Playwright easily handles several tabs, origins and browsers; Cypress gives direct access to the app's window.
61. Which Cypress practice is an anti-pattern?
Correct answer: Making tests depend on each other's data
Each test should set up its own state; then it can run alone and in any order.
62. Why are integration tests in the frontend often the best value?
Correct answer: They test real collaboration and stay fast enough
Unit tests of tiny components often check little; E2E is slow - integration sits in the sweet spot.
63. Which test type best fits “checkout works with the real backend and payment sandbox”?
Correct answer: E2E
Only an E2E test exercises the full stack; keep such tests for the most valuable flows.
64. What does a contract test check?
Correct answer: That provider and consumer agree on API formats
Consumer-driven contracts (e.g. Pact) are recorded by the frontend and verified against the backend in its CI.
65. What should you do with a flaky test you can't fix right away?
Correct answer: Quarantine it with an owner and fix the root cause soon
A suite that is often red “for no reason” teaches people to ignore failures, including real ones.
66. What are the common causes of flaky UI tests?
Correct answer: Async UI, shared state, real network and animations
Fix the cause: wait for conditions, isolate data, mock the network and clock, disable animations.
67. What does “Given–When–Then” correspond to in a test?
Correct answer: Arrange, Act, Assert
BDD tools (Cucumber) use it as a syntax; in plain tests it's just a structure for readability.
68. Why is deep nesting of
describeblocks with sharedletvariables problematic?Correct answer: Reading one test requires reading many hooks above it
Kent C. Dodds: prefer flat tests with explicit setup functions (“Avoid Nesting when you're Testing”).
69. What should a component test NOT assert?
Correct answer: Internal state values or the number of renders
Those are implementation details; refactoring them must not break tests.
70. How can automated accessibility checks be added to component tests?
const { container } = render(<Form />); expect(await axe(container)).toHaveNoViolations();Correct answer: With jest-axe, which catches part of the issues
Automated tools find roughly a third of a11y problems; keyboard and screen-reader checks are still needed.
71. What is component testing in Playwright or Cypress?
Correct answer: Mounting a single component in a real browser
Useful for things jsdom can't do: real layout, scrolling, canvas, CSS behaviour.
72. What is Vitest Browser Mode?
Correct answer: Running Vitest tests in a real browser instead of jsdom
It removes jsdom's gaps (layout, real events) while keeping the Vitest API.
73. What do asymmetric matchers like
expect.objectContaininggive you?expect(track).toHaveBeenCalledWith( "purchase", expect.objectContaining({ total: 30, id: expect.any(String) }), );Correct answer: They check only the parts that matter and ignore the rest
Others:
expect.arrayContaining,expect.stringMatching,expect.anything(). Tests stay precise without being brittle.74. How do you check that “Submit” is disabled until the form is valid?
const submit = screen.getByRole("button", { name: "Submit" }); expect(submit).toBeDisabled(); await user.type(screen.getByLabelText("Email"), "ann@example.com"); expect(submit).toBeEnabled();Correct answer: Assert
toBeDisabled, fill the form, asserttoBeEnabledtoBeDisabledalso covers buttons disabled by a parent<fieldset disabled>.75. How are retries usually configured in Playwright?
export default defineConfig({ retries: process.env.CI ? 2 : 0 });Correct answer: Only in CI, with passing retries reported as flaky
Retries soften infrastructure noise, but the flaky report must be watched - otherwise retries hide real bugs.