Testing Junior 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 main goal of automated tests?

    Correct answer: To give confidence that the code keeps working after changes

    Tests can show the presence of bugs, not their absence. Their value is fast feedback and safe refactoring: if behaviour breaks, a test fails before users notice.

  2. 2. What does a unit test check?

    Correct answer: A small isolated piece of code on its own

    Unit tests are fast and pinpoint the failing place. Their limit: they don't show whether the pieces work together.

  3. 3. What does an integration test check?

    Correct answer: That several units work correctly together

    In frontend, an integration test usually renders a feature (several components, state, router) and mocks only the network boundary.

  4. 4. What is an end-to-end (E2E) test?

    Correct answer: A test that drives the real app in a browser like a user

    E2E tests give the most confidence but are slower and more fragile. Typical tools: Playwright and Cypress.

  5. 5. What does the classic test pyramid recommend?

    Correct answer: Many unit tests, fewer integration and a few E2E tests

    The higher the level, the slower, more expensive and flakier the tests. The pyramid shape keeps the suite fast while still checking critical flows end to end.

  6. 6. What does the “testing trophy” by Kent C. Dodds put the most weight on?

    Correct answer: Integration tests, on top of static analysis

    “Write tests. Not too many. Mostly integration.” In UI code integration tests give the best ratio of confidence to cost.

  7. 7. Which layer of the testing trophy catches typos and wrong types before tests even run?

    Correct answer: Static analysis: TypeScript and ESLint

    Static tools give instant feedback in the editor and cost almost nothing per check.

  8. 8. What is a regression?

    Correct answer: A bug in functionality that used to work

    A good habit: when fixing a bug, first write a test that reproduces it. The test fails, the fix makes it pass, and the bug can't silently come back.

  9. 9. What does the Arrange–Act–Assert (AAA) pattern describe?

    Correct answer: Test structure: prepare, perform the action, check

    The same idea is called Given–When–Then in BDD. A clear structure makes tests easy to read and keeps each test focused on one behaviour.

  10. 10. What should a test check - behaviour or implementation details?

    Correct answer: Behaviour visible to the user or caller, so refactoring doesn't break tests

    Tests tied to implementation details fail on safe refactors (false negatives) and can pass when the user-visible result is broken (false positives).

  11. 11. What does test coverage measure?

    Correct answer: Which share of the code ran during the tests

    Coverage shows untested code but not test quality: a test without assertions still increases coverage.

  12. 12. Is 100% coverage a good goal on its own?

    Correct answer: No: it's expensive and doesn't guarantee meaningful checks

    Martin Fowler: coverage is useful for finding untested code, but a poor target. High coverage with weak assertions gives false confidence.

  13. 13. What are Jest and Vitest?

    Correct answer: JavaScript test runners with assertions and mocks built in

    Vitest is built on Vite and reuses its config and transforms; its API is largely compatible with Jest (describe, it, expect, mocks).

  14. 14. Which files does Jest pick up as tests by default?

    Correct answer: .test and .spec files, and files in __tests__

    The default is set by testMatch. Vitest uses a similar include pattern: **/*.{test,spec}.?(c|m)[jt]s?(x).

  15. 15. What do describe and it (test) do?

    Correct answer: describe groups related tests, it/test declares one test case

    it and test are aliases. Groups can have their own beforeEach/afterEach hooks.

  16. 16. What is the difference between toBe and toEqual?

    expect({ a: 1 }).toBe({ a: 1 });    // ?
    expect({ a: 1 }).toEqual({ a: 1 }); // ?

    Correct answer: toBe fails on a new object; toEqual passes on equal contents

    Use toBe for primitives and identity checks, toEqual for objects and arrays.

  17. 17. How does toStrictEqual differ from toEqual?

    Correct answer: It also checks undefined properties and object types

    expect({ a: undefined, b: 2 }).toEqual({ b: 2 }) passes, but toStrictEqual fails.

  18. 18. Why does this check fail and how do you fix it?

    expect(0.1 + 0.2).toBe(0.3);

    Correct answer: Floating-point rounding; use toBeCloseTo(0.3)

    toBeCloseTo compares with a given precision (2 decimal digits by default).

  19. 19. How do you check that a function throws an error?

    expect(() => parse("bad")).toThrow("Invalid input");

    Correct answer: Pass a function, so that expect can catch the error

    expect(parse("bad")) would throw before expect gets control and the test would fail with that error instead of checking it.

  20. 20. What does .not do in expect(value).not.toBeNull()?

    Correct answer: Inverts the matcher

    Any matcher can be negated: .not.toContain, .not.toHaveBeenCalled and so on.

  21. 21. Which matcher checks that an array contains an element?

    Correct answer: toContain

    toContain uses ===; to find an object by contents use toContainEqual. toMatch is for strings and regexes, toHaveProperty for object keys.

  22. 22. What is beforeEach used for?

    Correct answer: Running setup code before every test in the scope

    For one-time setup there is beforeAll; for cleanup - afterEach and afterAll.

  23. 23. What do it.only and it.skip do?

    Correct answer: only runs just the marked tests in the file, skip excludes a test

    Handy while debugging, but don't commit .only - it silently disables the other tests. Vitest fails a CI run that contains .only (allowOnly), and linters have rules against it.

  24. 24. How do you test an async function that returns a promise?

    test("loads user", async () => {
      const user = await fetchUser(1);
      expect(user.name).toBe("Ann");
    });

    Correct answer: Make the test async and await the result (or return the promise)

    If the promise is neither awaited nor returned, the test ends before the assertion runs and passes falsely.

  25. 25. How do you check that a promise rejects?

    Correct answer: await expect(fetchUser(-1)).rejects.toThrow("Not found")

    .resolves/.rejects unwrap the promise. Don't forget await (or return), otherwise the assertion isn't awaited.

  26. 26. What does watch mode (vitest / jest --watch) do?

    Correct answer: Reruns related tests on every save

    Vitest starts in watch mode by default in a terminal and uses Vite's module graph to rerun only affected tests.

  27. 27. Why is it useful that each test is independent?

    Correct answer: Tests can run in any order, and a failure has one cause

    Shared mutable state between tests causes order-dependent failures that are hard to debug. Reset state in beforeEach.

  28. 28. What is a good name for a test?

    Correct answer: One that describes the expected behaviour

    When a test fails in CI, its name is the first thing you read. It should tell what broke for the user.

  29. 29. Which environment do component tests usually run in under Jest/Vitest?

    Correct answer: jsdom or happy-dom - a DOM emulation in Node.js

    In Vitest it is set with environment: "jsdom"; in Jest - testEnvironment: "jsdom". The emulation has no real layout or rendering.

  30. 30. What is a mock in testing?

    Correct answer: A fake dependency you can control and inspect

    Strictly, “test doubles” are dummies, stubs, spies, mocks and fakes; in everyday speech all of them are called mocks.

  31. 31. What does jest.fn() / vi.fn() create?

    Correct answer: A mock function that records its calls

    Typical use: pass it as a callback prop and check that it was called.

  32. 32. How do you check that a callback was called with specific arguments?

    const onSave = vi.fn();
    render(<Form onSave={onSave} />);
    // ...user fills the form and submits

    Correct answer: expect(onSave).toHaveBeenCalledWith({ name: "Ann" })

    There is also toHaveBeenCalledTimes(n) and toHaveBeenLastCalledWith(...).

  33. 33. How do you make a mock return a value?

    Correct answer: mock.mockReturnValue(42)

    mockReturnValueOnce sets the value for one call only, and mockImplementation(fn) replaces the whole body.

  34. 34. What does jest.spyOn(obj, "method") / vi.spyOn do?

    Correct answer: Wraps a method to record calls, still calling the original

    Add .mockImplementation(...) to replace the behaviour, and restore the original with mockRestore() after the test.

  35. 35. What is a stub?

    Correct answer: A double that returns prepared answers

    Stubs feed data in; mocks are used to verify interactions (calls). Fakes are simplified working implementations, like an in-memory repository.

  36. 36. Why mock network requests in unit and integration tests?

    Correct answer: To make tests fast, deterministic and server-independent

    A real backend can be slow, down or return different data. The real integration with the API is checked separately - by E2E or contract tests.

  37. 37. What is MSW (Mock Service Worker)?

    Correct answer: A library that intercepts requests at the network level

    The app code keeps calling real fetch; MSW returns responses from handlers. The same handlers work in tests, Storybook and local development.

  38. 38. What does mockClear() (or vi.clearAllMocks()) do?

    Correct answer: Resets recorded calls but keeps the implementation

    Without clearing, calls from the previous test leak into the next one and toHaveBeenCalledTimes gives wrong numbers.

  39. 39. What is a risk of mocking too much?

    Correct answer: Tests pass while real parts no longer fit

    Every mock is an assumption about how the real dependency behaves. Mock the boundaries (network, time, randomness), not your own modules.

  40. 40. How do you make a test that uses Math.random() deterministic?

    Correct answer: Mock Math.random or inject the random source

    Random values, current time and network are the usual sources of non-determinism. Fix them in tests.

  41. 41. What is the main principle of Testing Library?

    Correct answer: Tests should resemble the way software is used

    So tests find elements the way a user does - by role, label and text - and interact through events.

  42. 42. What does render from React Testing Library do?

    Correct answer: Renders a component into a container in document.body

    After each test RTL unmounts the component automatically (cleanup), if the runner exposes a global afterEach.

  43. 43. Why use screen instead of queries returned by render?

    Correct answer: It's bound to document.body, so no destructuring is needed

    Testing Library recommends screen: tests are shorter and you can add queries without changing the render line.

  44. 44. Which query does Testing Library recommend first?

    Correct answer: getByRole

    Priority: queries accessible to everyone (ByRole, ByLabelText, ByPlaceholderText, ByText, ByDisplayValue), then semantic (ByAltText, ByTitle), and only then ByTestId.

  45. 45. How do you find the “Save” button?

    Correct answer: screen.getByRole("button", { name: "Save" })

    name is the accessible name: the button's text, aria-label or aria-labelledby. Such a query also checks that the button is accessible.

  46. 46. What is the difference between getBy, queryBy and findBy?

    Correct answer: getBy throws, queryBy returns null, findBy waits

    Each also has an All version (getAllBy, …) that returns an array.

  47. 47. How do you check that an element is NOT on the page?

    Correct answer: expect(screen.queryByText("Error")).not.toBeInTheDocument()

    getBy would throw before the assertion runs, and findBy returns a promise, which is always truthy.

  48. 48. Which query should you use for an element that appears after data loads?

    Correct answer: await screen.findByText("Ann")

    findBy retries the query until the element appears or the timeout (1000 ms by default) runs out.

  49. 49. Where do matchers like toBeInTheDocument, toBeVisible and toHaveValue come from?

    Correct answer: From @testing-library/jest-dom

    Import @testing-library/jest-dom (or @testing-library/jest-dom/vitest) in a setup file. They give clearer error messages than manual DOM checks.

  50. 50. What is better for simulating user actions: fireEvent or user-event?

    Correct answer: user-event: it reproduces the whole chain of real events

    fireEvent.click dispatches one event. userEvent.click also moves the pointer, focuses and respects disabled and pointer-events.

  51. 51. How do you type text into an input with user-event v14?

    const user = userEvent.setup();
    render(<Login />);
    await user.type(screen.getByLabelText("Email"), "ann@example.com");

    Correct answer: As shown: create user with setup() and await the call

    In v14 all methods return promises. Setting value directly skips the events React listens to.

  52. 52. How do you find an input by its label?

    <label htmlFor="email">Email</label>
    <input id="email" />

    Correct answer: screen.getByLabelText("Email")

    The query fails if the label isn't connected to the input - a useful accessibility check. getByRole("textbox", { name: "Email" }) works too.

  53. 53. When is getByTestId appropriate?

    Correct answer: When an element can't be found by role, label or text

    A user doesn't see data-testid, so this query doesn't check accessibility. Keep it as a last resort.

  54. 54. What is wrong with this test?

    const { container } = render(<Counter />);
    container.querySelector(".increment").click();
    expect(container.querySelector(".value").textContent).toBe("1");

    Correct answer: It depends on CSS classes, not on roles and text

    Renaming a class breaks the test although the user sees no change.

  55. 55. How do you check the result of clicking a counter button?

    const user = userEvent.setup();
    render(<Counter />);
    await user.click(screen.getByRole("button", { name: "+" }));

    Correct answer: expect(screen.getByText("Count: 1")).toBeInTheDocument()

    Check what the user sees, not the component's internal state.

  56. 56. What does screen.debug() do?

    Correct answer: Prints the current DOM to the console

    There is also screen.logTestingPlaygroundURL() - it gives a link where you can pick the best query.

  57. 57. What does toHaveBeenCalledTimes(1) check on a prop callback after a click?

    const onClick = vi.fn();
    render(<Button onClick={onClick}>Ok</Button>);
    await userEvent.setup().click(screen.getByRole("button"));
    expect(onClick).toHaveBeenCalledTimes(1);

    Correct answer: That the callback was called exactly once

    Passing a mock as a prop is the simplest way to test what a component reports to its parent.

  58. 58. What does a snapshot test do?

    Correct answer: Saves serialized output, then compares later runs to it

    An intentional change is accepted with -u (update). Large snapshots are easy to approve without reading - prefer small, focused ones.

  59. 59. Why do Testing Library queries by role also improve accessibility?

    Correct answer: If a test can't find it by role, a screen reader may not either

    A <div onClick> instead of <button> has no button role, and such a test fails - prompting you to fix the markup.

  60. 60. What are Playwright and Cypress used for?

    Correct answer: E2E tests that drive a real browser

    Both open the app, click, type and check the result like a user.

  61. 61. Which browsers can Playwright run tests in?

    Correct answer: Chromium, Firefox and WebKit (the engine behind Safari)

    Playwright downloads its own browser builds; one test file can run in all three via projects in the config.

  62. 62. What is the recommended way to find a button in Playwright?

    Correct answer: page.getByRole("button", { name: "Sign in" })

    User-facing locators survive markup changes; long CSS and XPath chains break on any refactor.

  63. 63. Do you need sleep/waitForTimeout before clicking in Playwright?

    Correct answer: No: actions wait until the element is ready

    Fixed waits make tests slow and still flaky. Rely on auto-waiting and web-first assertions.

  64. 64. What does await expect(page.getByText("Saved")).toBeVisible() do in Playwright?

    Correct answer: Retries the check until the text becomes visible or the timeout expires

    These are web-first assertions: they wait for the condition, so async UI doesn't need manual waits.

  65. 65. What does headless mode mean?

    Correct answer: The browser runs without a visible window

    Locally you can run Playwright with --headed or --ui to watch the test.

  66. 66. How do you find an element in Cypress by a dedicated test attribute?

    Correct answer: cy.get('[data-cy="submit"]')

    Cypress recommends data-cy/data-test attributes: they don't change with styling. cy.contains("Submit") searches by text.

  67. 67. Why should E2E tests be few and focused on key user flows?

    Correct answer: They are slow, costly to maintain and prone to flakiness

    Typical E2E candidates: sign-in, checkout, registration - flows where a break costs the most.

  68. 68. What is a flaky test?

    Correct answer: A test that passes or fails without code changes

    Common causes: timing and race conditions, shared state, real network, current time. Flaky tests destroy trust in the suite.

  69. 69. What does playwright codegen do?

    Correct answer: Records your browser actions as test code

    A good starting point; the generated code still needs meaningful assertions and cleanup.

  70. 70. What is TDD (test-driven development)?

    Correct answer: Failing test first, minimal code, then refactoring

    TDD helps design small, testable units and gives a test for every requirement.

  71. 71. Where do tests usually run automatically?

    Correct answer: In CI on every push, blocking the merge if they fail

    Fast tests (lint, types, unit) usually run first, slower E2E after them or in parallel.

  72. 72. Which of these is the best candidate for a unit test?

    Correct answer: A pure function that formats prices

    Pure functions with many edge cases are cheap to test thoroughly with unit tests.

  73. 73. What does test.each / it.each do?

    test.each([
      [1, 1, 2],
      [2, 3, 5],
    ])("add(%i, %i) = %i", (a, b, expected) => {
      expect(add(a, b)).toBe(expected);
    });

    Correct answer: Runs the same test with different data sets

    Parameterized tests remove copy-paste and make edge cases easy to add.

  74. 74. What should a single test ideally check?

    Correct answer: One behaviour, even with several related assertions

    One scenario per test makes failures easy to understand. Several assertions about the same result are fine.

  75. 75. Why doesn't this test catch a bug?

    test("saves", () => {
      save(data).then((result) => {
        expect(result.ok).toBe(true);
      });
    });

    Correct answer: The promise isn't awaited, so the test ends first

    Add return or make the test async and await the promise.

  76. 76. What does the expect.assertions(n) call guarantee?

    Correct answer: That exactly n assertions ran in the test

    If an assertion inside a callback never runs, the test fails instead of passing silently.

  77. 77. Which test is the right place to check that a form shows “Required” when submitted empty?

    Correct answer: A component test with Testing Library

    Validation is a UI behaviour that doesn't need a real backend: a fast RTL test covers it well.

  78. 78. Why test a custom hook through a component (or renderHook) rather than calling it directly?

    Correct answer: Hooks can only be called during React rendering

    A direct call breaks the rules of hooks. renderHook renders a tiny test component around the hook.