Testing quick reference for interviews

The essentials of the topic on a couple of pages: key concepts by section and the pitfalls interviewers like to ask about.

Strategy and test levels

Levels.
A unit test checks one function or component in isolation. An integration test checks several parts working together, like a form with validation and an API call. An E2E test drives the real app in a browser, as a user would.
Pyramid.
Many fast unit tests, fewer integration tests, very few slow E2E tests. The higher the level, the more confidence per test, but also the more cost, time and flakiness.
Testing trophy.
Kent C. Dodds's shape for the frontend: static checks at the base (TypeScript, ESLint catch typos and wrong types), then unit, a wide integration layer and a thin E2E top. Integration tests give the best value: they're close to real use and still fast.
Honeycomb and sizes.
The honeycomb (microservices) puts integration tests at the center. Google's test sizes (small, medium, large) are based on resources: one process, one machine, or the network. Words like "unit" mean different things in different teams, so agree on terms.
Behavior, not implementation.
Test what the user or caller sees: text, roles, returned values. Don't assert on state, private methods or the number of renders: such tests break on every refactor and miss real bugs.
Choosing the level.
Put a check at the lowest level that can catch the bug: logic in unit tests, component behavior in integration tests, critical flows across the real backend (sign up, checkout) in E2E.

Test structure

Arrange-Act-Assert.
Prepare the data, perform one action, check the result. Given-When-Then from BDD is the same three steps.
describe and it.
describe groups tests, it (alias test) declares one case. it.only runs only this test, it.skip skips it; don't commit either.
Hooks.
beforeEach and afterEach run around every test, beforeAll and afterAll once per file or block. Deep describe nesting with shared let variables makes tests hard to read: prefer small setup functions.
Independence.
Each test sets up its own state and passes alone, in any order. Then tests can run in parallel, and a failure points to one cause.
Naming and focus.
A name describes behavior: "shows an error when the email is empty". One test checks one behavior, even if that takes several expect calls.
Parametrized tests.
it.each runs the same test over a table of inputs and expected results.
Files.
Jest and Vitest pick up *.test.* and *.spec.* files and, in Jest, files in __tests__. Watch mode reruns tests related to changed files.
it.each([
  [0, "0 items"],
  [1, "1 item"],
  [5, "5 items"],
])("formats %i as %s", (count, expected) => {
  expect(formatCount(count)).toBe(expected);
});

Matchers and async code

toBe and toEqual.
toBe compares with Object.is: for primitives and the same reference. toEqual compares structure recursively. toStrictEqual also checks undefined properties, sparse arrays and class types.
Common matchers.
toContain for an element in an array or a substring, toHaveLength, toMatch for a regex, toBeCloseTo for floats, .not to invert any matcher.
Asymmetric matchers.
expect.objectContaining, expect.arrayContaining, expect.any(Number), expect.stringMatching check only what matters and ignore ids, dates and other noise.
Errors.
Wrap the call in a function: expect(() => parse("")).toThrow("empty"). Without the wrapper the error is thrown before expect runs.
Promises.
Make the test async and await the result, or use await expect(promise).resolves and .rejects.toThrow(). A promise that isn't awaited or returned lets the test finish early and pass.
expect.assertions.
expect.assertions(1) fails the test if the expected number of assertions didn't run, for example when code in a catch was never reached.
it("rejects an unknown user", async () => {
  await expect(loadUser("nope")).rejects.toThrow("Not found");
});

expect(order).toEqual({
  id: expect.any(String),
  items: expect.arrayContaining([{ sku: "A1", qty: 2 }]),
});

Mocks, stubs and spies

Terms.
A test double replaces a real dependency. A stub returns prepared answers, a mock also records calls to check them, a spy wraps a real function, a fake is a simple working implementation such as an in-memory repository.
vi.fn and jest.fn.
Create a mock function: mockReturnValue, mockResolvedValue, mockImplementation, mockImplementationOnce for a single call. Check calls with toHaveBeenCalledWith(...) and toHaveBeenCalledTimes(n).
spyOn.
vi.spyOn(obj, "method") tracks calls to an existing method and can replace its implementation; mockRestore() brings the original back. It can't replace an ESM export called inside the same module.
Clear, reset, restore.
mockClear forgets calls, mockReset also resets the implementation, mockRestore additionally returns the original method for a spy. clearMocks or restoreMocks in the config does it before every test.
vi.mock.
Replaces a whole module and is hoisted to the top of the file, so its factory can't use variables declared in the test file; use vi.hoisted. To replace one export and keep the rest, spread await importOriginal() in the factory.
How much to mock.
Mock the boundaries: network, time, randomness, browser APIs. "Don't mock what you don't own": wrap third-party libraries in your own module, or use a fake. Too many mocks test the mocks, not the code.
Dependency injection.
A function that gets its dependencies as parameters (createService({ api, clock })) is easy to test with fakes, without module mocking.
vi.mock("./analytics", async (importOriginal) => ({
  ...(await importOriginal()),
  track: vi.fn(),
}));

const onSave = vi.fn().mockResolvedValue({ ok: true });
await user.click(screen.getByRole("button", { name: "Save" }));
expect(onSave).toHaveBeenCalledWith({ title: "Draft" });

Time and determinism

Fake timers.
vi.useFakeTimers() replaces setTimeout, setInterval and Date. vi.advanceTimersByTime(1000) moves time forward by a second, vi.runAllTimers() runs every pending timer, including ones they schedule.
Fixed date.
vi.setSystemTime(new Date("2026-01-15T10:00:00Z")) makes "today" stable. Set the time zone explicitly (TZ=UTC) and pass a locale to Intl so the test passes on any machine.
Randomness.
Mock Math.random or crypto.randomUUID, or pass a seeded generator into the code.
user-event with fake timers.
userEvent.setup({ advanceTimers: vi.advanceTimersByTime }), otherwise user-event's internal delays wait for timers that never fire.
Debounce.
Type, check that the request wasn't sent yet, advance the timers by the debounce delay, then check that exactly one request went out.
Hanging tests.
With fake timers, an awaited promise that waits on setTimeout never resolves until you advance the timers. Restore real timers with vi.useRealTimers() in afterEach.

API mocking with MSW

What it is.
Mock Service Worker intercepts requests at the network level: a Service Worker in the browser, request interception in Node.js. The component uses its real fetch or axios code.
Why not mock fetch.
The test doesn't depend on which HTTP client is used, checks real URLs, headers and bodies, and the same handlers work in unit tests, Storybook and local development.
Setup in Node.js.
setupServer(...handlers), then server.listen() in beforeAll, server.resetHandlers() in afterEach, server.close() in afterAll. onUnhandledRequest: "error" catches requests without a handler.
Per-test overrides.
server.use(http.get("/api/user", () => HttpResponse.json(null, { status: 500 }))) makes only this test get an error; resetHandlers removes it afterwards.
Checking requests.
Prefer checking the result on the screen. When the payload matters, read await request.json() inside the handler and assert on it.
Drift.
Hand-written handlers can drift from the real API. Generate them or their types from an OpenAPI schema, or add contract tests.
const server = setupServer(
  http.get("/api/user", () => HttpResponse.json({ name: "Ann" })),
);

beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Testing Library

Principle.
"The more your tests resemble the way your software is used, the more confidence they can give you." Find elements the way users do: by role, label and text.
Query priority.
getByRole with name first, then getByLabelText, getByPlaceholderText, getByText, getByDisplayValue, and getByTestId last, when nothing else fits. Role queries also check that the markup is accessible.
get, query, find.
getBy throws if there's no element, queryBy returns null (for checking absence), findBy returns a promise and waits up to 1 second. Each has an All version for lists.
Waiting.
findBy is getBy plus waitFor. Inside waitFor put one assertion and no side effects: the callback runs many times. To wait for a spinner to go away, use waitForElementToBeRemoved.
user-event.
const user = userEvent.setup(), then await user.click(...) and await user.type(input, "text"). It fires the full chain of events like a real user, unlike the single event of fireEvent.
screen and within.
screen searches the whole document, within(row).getByText(...) only inside one element, such as a table row or dialog.
jest-dom matchers.
@testing-library/jest-dom adds toBeInTheDocument, toBeVisible, toBeDisabled, toBeChecked, toHaveValue, toHaveAccessibleName. screen.debug() prints the DOM, logRoles lists roles.
it("adds a todo", async () => {
  const user = userEvent.setup();
  render(<Todos />);

  await user.type(screen.getByLabelText("New todo"), "Buy milk");
  await user.click(screen.getByRole("button", { name: "Add" }));

  expect(await screen.findByText("Buy milk")).toBeInTheDocument();
  expect(screen.queryByText("No todos yet")).not.toBeInTheDocument();
});

Testing React

Providers.
Components that need a router, store, theme or QueryClient are rendered with a wrapper, usually through your own renderWithProviders helper. Create a new QueryClient with retry: false for every test.
Hooks.
A custom hook is tested through a component that uses it or with renderHook, which returns result.current and rerender. Don't mock useState or other React hooks: that tests React, not your code.
act().
Makes sure state updates and effects are applied before assertions. Testing Library wraps render and events in it. The "not wrapped in act" warning usually means an update happened after the test finished: wait for it with findBy.
Props, portals, errors.
rerender(<Price value={20} />) checks the reaction to new props. A modal in a portal is still found through screen. For error boundaries, silence console.error with a spy during the test.
Suspense and RSC.
With Suspense, check the fallback first, then findBy the loaded content. Async Server Components are covered better by E2E tests; a Server Action is a function that can be called directly with mocked dependencies.
Snapshots.
toMatchSnapshot saves output and compares it later. Large snapshots get updated without reading and hide changes. Small toMatchInlineSnapshot values for serialized data are fine.

Environment and configuration

DOM environment.
Component tests run in Node.js with jsdom or happy-dom. happy-dom is faster but less complete. Neither has layout: no real sizes, scrolling, CSS media queries or IntersectionObserver.
Browser Mode.
Vitest Browser Mode and component tests in Playwright or Cypress run components in a real browser, where layout and browser APIs are real.
Setup files.
setupFiles in Vitest and setupFilesAfterEnv in Jest run before each test file: jest-dom matchers, MSW server, global mocks. globals: true in Vitest makes describe, it and expect available without imports.
Isolation.
Each test file runs in its own module environment, so module state doesn't leak between files. Inside a file it does: vi.resetModules() plus a dynamic import gives a fresh copy.
Pools and projects.
Vitest's threads pool is faster, forks is more compatible with native modules. projects runs different configs (jsdom for components, node for the server) in one run.
Coverage.
Providers: v8 (fast, built into the engine) and istanbul. Branch coverage shows untaken if and ?: branches that line coverage misses. A threshold in the config fails the run when coverage drops.

Playwright

Locators.
page.getByRole("button", { name: "Save" }), getByLabel, getByText. A locator is resolved anew on every action. It is strict: an action on a locator that matches several elements fails. Narrow with .filter({ hasText: "Ann" }).
Auto-waiting.
Actions wait for the element to be visible, stable and enabled, so waitForTimeout isn't needed. Web-first assertions like await expect(locator).toBeVisible() retry until timeout, unlike expect(await locator.isVisible()).
Isolation and fixtures.
Each test gets a fresh browser context: its own cookies and storage. Fixtures (page, request, your own) provide setup and teardown on demand and compose better than beforeEach.
Login once.
A setup project logs in and saves storageState to a file, and other projects reuse it. Data for tests is created through the API, not the UI.
Network and time.
page.route("**/api/user", (route) => route.fulfill({ json: user })) mocks a response. page.clock controls time. routeFromHAR replays recorded traffic.
Debugging.
The trace viewer shows each step with DOM snapshots, network and console. codegen records actions into code. test.step names steps in reports, expect.soft keeps the test running after a failed check.
Scaling.
Workers are parallel processes on one machine, shards (--shard=1/4) split the suite between CI machines. webServer in the config starts the app before the tests. projects run the suite in Chromium, Firefox and WebKit.
test("user saves a profile", async ({ page }) => {
  await page.goto("/profile");
  await page.getByLabel("Name").fill("Ann");
  await page.getByRole("button", { name: "Save" }).click();
  await expect(page.getByRole("status")).toHaveText("Saved");
});

Cypress

Command queue.
Commands like cy.get don't return elements: they are queued and run later. That's why const text = cy.get(...) doesn't work and async/await doesn't apply; values are taken in .then().
Retry-ability.
Queries and the assertions after them (cy.get(".item").should("have.length", 3)) retry until timeout. Code inside .then() doesn't retry; put the check in .should(callback) instead.
Network.
cy.intercept("GET", "/api/user").as("user") and cy.wait("@user") wait for a specific request instead of a fixed cy.wait(2000). intercept can also return a stubbed response.
Sessions and origins.
cy.session() caches login between tests. cy.origin() runs commands on another domain, for example an external login page.
Architecture.
Cypress runs inside the browser next to the app, which gives an interactive runner with time travel. Playwright controls the browser from outside and handles several tabs, domains and browsers more easily.
Practices.
Select by data-cy or by role and text, not by CSS classes. Don't depend on the state left by the previous test, and don't log in through the UI in every test.

Flaky tests and CI

Flaky test.
Passes and fails on the same code. Common causes: fixed waits, race conditions with async rendering, shared state and data between tests, the real network, time and random values, animations.
Order dependence.
A test that passes alone but fails in the file depends on state from other tests: mocks not reset, a shared object, data in the DOM or storage.
Handling.
A flaky test you can't fix now is quarantined (skipped with a ticket) instead of being rerun until green. Automatic retries hide real races unless flaky results are tracked.
Parallel data.
Tests running in parallel against a shared environment create their own unique data (an id or timestamp in the name) and don't rely on shared records.
Pipeline.
Fastest checks first: types and lint, then unit and integration, E2E last. --ci in Jest doesn't write new snapshots, vitest --changed runs only tests affected by changes, but misses indirect dependencies.
Suite health.
Look at the share of flaky runs, run time and bugs that escape to production, not at the number of tests or the coverage percentage.

Beyond regular tests

Accessibility checks.
jest-axe or @axe-core/playwright finds missing labels, invalid ARIA and contrast problems (in a real browser). They catch about a third of issues; keyboard navigation and screen reader output need manual checks.
Visual tests.
toHaveScreenshot or Storybook with Chromatic compare screenshots pixel by pixel. To reduce noise, fix fonts, disable animations, mask dynamic content and render in the same environment.
Contract tests.
Check that the frontend and the API agree on requests and responses (Pact or schema checks) without running both together.
Mutation testing.
Stryker changes the code (flips > to >=, removes calls) and checks whether tests fail. Surviving mutants show tests that run code but don't really check it.
Property-based testing.
fast-check generates hundreds of inputs and checks a rule that must always hold, such as "parsing a formatted value gives the original", and shrinks a failure to the smallest example.
Coverage as a KPI.
A coverage target leads to tests without real assertions. Coverage shows which code is untested, not that the tested code is correct.

Common pitfalls

  • A promise that isn't awaited or returned lets the test finish before the check: it passes even when the code is broken.
  • expect(fn()).toThrow() throws before expect runs. Pass a function: expect(() => fn()).toThrow().
  • getBy to check absence throws. Use queryBy with .not.toBeInTheDocument().
  • getBy for content that appears after loading fails at once. Use await findBy.
  • Side effects inside waitFor, like a click, are repeated on every retry.
  • Fixed waits (sleep, waitForTimeout, cy.wait(2000)) make tests slow and flaky. Wait for an element, a request or an assertion.
  • vi.mock is hoisted: its factory can't use variables from the test file without vi.hoisted.
  • Mocks not reset between tests leak calls and implementations into the next test. Turn on clearMocks or restoreMocks.
  • toBe on objects compares references: two equal objects are not toBe each other. Use toEqual.
  • Tests that check state, private methods or class names break on refactoring but miss real bugs.
  • A data-testid for everything hides accessibility problems that getByRole would catch.
  • Committed it.only silently skips the rest of the file in CI.

Cheat sheet