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.
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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Which files does Jest pick up as tests by default?
Correct answer:
.testand.specfiles, and files in__tests__The default is set by
testMatch. Vitest uses a similarincludepattern:**/*.{test,spec}.?(c|m)[jt]s?(x).15. What do
describeandit(test) do?Correct answer:
describegroups related tests,it/testdeclares one test caseitandtestare aliases. Groups can have their ownbeforeEach/afterEachhooks.16. What is the difference between
toBeandtoEqual?expect({ a: 1 }).toBe({ a: 1 }); // ? expect({ a: 1 }).toEqual({ a: 1 }); // ?Correct answer:
toBefails on a new object;toEqualpasses on equal contentsUse
toBefor primitives and identity checks,toEqualfor objects and arrays.17. How does
toStrictEqualdiffer fromtoEqual?Correct answer: It also checks
undefinedproperties and object typesexpect({ a: undefined, b: 2 }).toEqual({ b: 2 })passes, buttoStrictEqualfails.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)toBeCloseTocompares with a given precision (2 decimal digits by default).19. How do you check that a function throws an error?
expect(() => parse("bad")).toThrow("Invalid input");Correct answer: Pass a function, so that
expectcan catch the errorexpect(parse("bad"))would throw beforeexpectgets control and the test would fail with that error instead of checking it.20. What does
.notdo inexpect(value).not.toBeNull()?Correct answer: Inverts the matcher
Any matcher can be negated:
.not.toContain,.not.toHaveBeenCalledand so on.21. Which matcher checks that an array contains an element?
Correct answer:
toContaintoContainuses===; to find an object by contents usetoContainEqual.toMatchis for strings and regexes,toHavePropertyfor object keys.22. What is
beforeEachused for?Correct answer: Running setup code before every test in the scope
For one-time setup there is
beforeAll; for cleanup -afterEachandafterAll.23. What do
it.onlyandit.skipdo?Correct answer:
onlyruns just the marked tests in the file,skipexcludes a testHandy 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. 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
asyncandawaitthe result (or return the promise)If the promise is neither awaited nor returned, the test ends before the assertion runs and passes falsely.
25. How do you check that a promise rejects?
Correct answer:
await expect(fetchUser(-1)).rejects.toThrow("Not found").resolves/.rejectsunwrap the promise. Don't forgetawait(orreturn), otherwise the assertion isn't awaited.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. 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. 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. 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. 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. 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. 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 submitsCorrect answer:
expect(onSave).toHaveBeenCalledWith({ name: "Ann" })There is also
toHaveBeenCalledTimes(n)andtoHaveBeenLastCalledWith(...).33. How do you make a mock return a value?
Correct answer:
mock.mockReturnValue(42)mockReturnValueOncesets the value for one call only, andmockImplementation(fn)replaces the whole body.34. What does
jest.spyOn(obj, "method")/vi.spyOndo?Correct answer: Wraps a method to record calls, still calling the original
Add
.mockImplementation(...)to replace the behaviour, and restore the original withmockRestore()after the test.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. 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. 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. What does
mockClear()(orvi.clearAllMocks()) do?Correct answer: Resets recorded calls but keeps the implementation
Without clearing, calls from the previous test leak into the next one and
toHaveBeenCalledTimesgives wrong numbers.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. How do you make a test that uses
Math.random()deterministic?Correct answer: Mock
Math.randomor inject the random sourceRandom values, current time and network are the usual sources of non-determinism. Fix them in tests.
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. What does
renderfrom React Testing Library do?Correct answer: Renders a component into a container in
document.bodyAfter each test RTL unmounts the component automatically (
cleanup), if the runner exposes a globalafterEach.43. Why use
screeninstead of queries returned byrender?Correct answer: It's bound to
document.body, so no destructuring is neededTesting Library recommends
screen: tests are shorter and you can add queries without changing therenderline.44. Which query does Testing Library recommend first?
Correct answer:
getByRolePriority: queries accessible to everyone (
ByRole,ByLabelText,ByPlaceholderText,ByText,ByDisplayValue), then semantic (ByAltText,ByTitle), and only thenByTestId.45. How do you find the “Save” button?
Correct answer:
screen.getByRole("button", { name: "Save" })nameis the accessible name: the button's text,aria-labeloraria-labelledby. Such a query also checks that the button is accessible.46. What is the difference between
getBy,queryByandfindBy?Correct answer:
getBythrows,queryByreturnsnull,findBywaitsEach also has an
Allversion (getAllBy, …) that returns an array.47. How do you check that an element is NOT on the page?
Correct answer:
expect(screen.queryByText("Error")).not.toBeInTheDocument()getBywould throw before the assertion runs, andfindByreturns a promise, which is always truthy.48. Which query should you use for an element that appears after data loads?
Correct answer:
await screen.findByText("Ann")findByretries the query until the element appears or the timeout (1000 ms by default) runs out.49. Where do matchers like
toBeInTheDocument,toBeVisibleandtoHaveValuecome from?Correct answer: From
@testing-library/jest-domImport
@testing-library/jest-dom(or@testing-library/jest-dom/vitest) in a setup file. They give clearer error messages than manual DOM checks.50. What is better for simulating user actions:
fireEventoruser-event?Correct answer:
user-event: it reproduces the whole chain of real eventsfireEvent.clickdispatches one event.userEvent.clickalso moves the pointer, focuses and respectsdisabledandpointer-events.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
userwithsetup()andawaitthe callIn v14 all methods return promises. Setting
valuedirectly skips the events React listens to.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. When is
getByTestIdappropriate?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. 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. 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. 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. 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. 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. 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 nobuttonrole, and such a test fails - prompting you to fix the markup.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. 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
projectsin the config.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. Do you need
sleep/waitForTimeoutbefore 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. 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. What does headless mode mean?
Correct answer: The browser runs without a visible window
Locally you can run Playwright with
--headedor--uito watch the test.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-testattributes: they don't change with styling.cy.contains("Submit")searches by text.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. 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. What does
playwright codegendo?Correct answer: Records your browser actions as test code
A good starting point; the generated code still needs meaningful assertions and cleanup.
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. 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. 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. What does
test.each/it.eachdo?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. 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. 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
returnor make the testasyncandawaitthe promise.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. 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. 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.
renderHookrenders a tiny test component around the hook.