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.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 1. What is the difference between findBy… and waitFor?

    Correct answer: findBy waits for an element; waitFor retries any callback

    findByRole(...) is literally waitFor(() => getByRole(...)). Use findBy to wait for an element and waitFor for other assertions.

  2. 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 waitFor repeat on every retry

    The callback may run many times, so it should contain only assertions, ideally a single one.

  3. 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. 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 render and events in act. The fix is usually to wait for the final UI state with findBy/waitFor, not to add act manually.

  5. 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. 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 clock

    Without it, user-event's delay waits on a setTimeout that never fires and the test times out.

  7. 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. 8. What does vi.runAllTimers() do differently from vi.advanceTimersByTime(1000)?

    Correct answer: It runs all pending timers until none are left

    With an endless setInterval, runAllTimers gives up after a limit of iterations - use runOnlyPendingTimers or advance by time.

  9. 9. How do you fix the current date in a test?

    Correct answer: vi.useFakeTimers() with vi.setSystemTime(...)

    Code that shows “today” or computes expiry otherwise fails on certain dates or in other time zones.

  10. 10. Why can vi.mock("./api") be written below the imports and still work?

    Correct answer: Vitest hoists vi.mock calls above the imports

    jest.mock is hoisted by babel-jest the same way.

  11. 11. Why does this mock factory fail?

    const user = { name: "Ann" };
    vi.mock("./api", () => ({ getUser: () => user }));

    Correct answer: The hoisted factory runs before user is initialized

    const user = vi.hoisted(() => ({ name: "Ann" })) is hoisted together with the mock. Jest allows only variables prefixed with mock.

  12. 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. 13. What is the difference between mockClear, mockReset and mockRestore?

    Correct answer: Clear wipes calls; reset also the implementation; restore the original

    Config options clearMocks, mockReset and restoreMocks apply them automatically before each test.

  14. 14. What does mockImplementationOnce allow?

    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. 15. Where do manual mocks for a node module live in Jest?

    Correct answer: In a __mocks__ folder next to node_modules

    Node module mocks in root __mocks__ are applied automatically; mocks for your own modules need an explicit jest.mock(path).

  16. 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.mock or move the dependency to another module / inject it.

  17. 17. Why is MSW often preferred over mocking fetch/axios directly?

    Correct answer: Tests don't depend on the HTTP client, and real request code runs

    Switching from axios to fetch doesn't break tests that mock at the network level.

  18. 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. 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.use override inside that test

    Runtime handlers take priority over the initial ones - a neat way to test error states.

  20. 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. 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 wrapper option

    Testing Library docs recommend re-exporting a custom render from a test utils module.

  22. 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 queries

    Index-based queries break when the order changes; within keeps the test meaningful.

  23. 23. What does renderHook return?

    const { result } = renderHook(() => useCounter());
    act(() => result.current.increment());
    expect(result.current.count).toBe(1);

    Correct answer: An object whose result.current holds the latest value

    Updates from outside React events must be wrapped in act. For hooks used by one component, testing that component is often better.

  24. 24. How do you test that a component reacts to new props?

    Correct answer: Call rerender(<Comp value="new" />) returned by render

    rerender updates the same tree, so state and effects behave like in the app.

  25. 25. How do you find a heading of a specific level?

    Correct answer: screen.getByRole("heading", { level: 2, name: "Settings" })

    ByRole supports options like level, checked, pressed, expanded, selected - they check ARIA state too.

  26. 26. Why can getByRole miss 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. 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. 28. How do you test a component that uses TanStack Query?

    Correct answer: Use a fresh QueryClient per test and MSW for the network

    A shared client leaks cache between tests; retries make error tests slow.

  29. 29. How do you test a component that depends on the current route (React Router)?

    Correct answer: Render it in a MemoryRouter with initialEntries

    A memory router gives a real navigation context without a browser URL.

  30. 30. How do you check that a checkbox is checked?

    Correct answer: expect(screen.getByRole("checkbox", { name: "Agree" })).toBeChecked()

    The checked attribute reflects only the initial state; toBeChecked checks the current state and also works with aria-checked.

  31. 31. What does toHaveAccessibleName check?

    Correct answer: The name that assistive technologies announce

    Useful for icon buttons: <button aria-label="Close">×</button> must be announced as “Close”.

  32. 32. How can you find the best query for an element quickly?

    Correct answer: screen.logTestingPlaygroundURL() or logRoles(container)

    logRoles prints all roles in the tree with their accessible names.

  33. 33. What is wrong with calling cleanup manually in afterEach?

    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. 34. Why is getByRole slower than getByText, and what to do about it?

    Correct answer: It computes the accessibility tree; scope it with within

    In most suites the difference is negligible, and the confidence gained is worth it.

  35. 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. 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 .snap files.

  37. 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. 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. 39. Which coverage providers does Vitest support?

    Correct answer: v8 (default) and istanbul

    V8 uses the engine's native coverage without instrumentation; Istanbul instruments code. lcov is a report format.

  40. 40. What is a setup file (setupFiles in Vitest, setupFilesAfterEnv in Jest) used for?

    Correct answer: Shared setup, such as matchers, MSW and polyfills

    Jest's setupFilesAfterEnv runs after the test framework is installed, so expect.extend and hooks like afterEach are available there.

  41. 41. What does globals: true in Vitest config do?

    Correct answer: Makes describe, it, expect and vi available without imports

    Without it you import them from vitest explicitly; add vitest/globals to TS types when enabling it.

  42. 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. 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. 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. 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 chaining

    filter also supports has, hasNot and hasNotText.

  46. 46. Why is expect(await locator.isVisible()).toBe(true) worse than await 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. 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.route and route.fulfill

    route.continue() lets the request through (optionally modified), route.abort() simulates a network failure.

  48. 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 storageState

    The saved cookies and localStorage are loaded into each new browser context.

  49. 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. 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. 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.extend share setup (logged-in page, page objects) without beforeEach boilerplate.

  52. 52. How do you start the app automatically before Playwright tests?

    Correct answer: Configure webServer in playwright.config

    reuseExistingServer: !process.env.CI uses a running dev server locally and starts a fresh one in CI.

  53. 53. What does expect.poll do 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.poll covers non-UI values.

  54. 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. 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. 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. 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 click don't. Avoid long chains of actions between queries.

  58. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 68. Why is deep nesting of describe blocks with shared let variables 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. 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. 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. 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. 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. 73. What do asymmetric matchers like expect.objectContaining give 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. 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, assert toBeEnabled

    toBeDisabled also covers buttons disabled by a parent <fieldset disabled>.

  75. 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.