devsetswww.devsets.com/en/topics/testing/notes
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.
describegroups tests,it(aliastest) declares one case.it.onlyruns only this test,it.skipskips it; don't commit either.- Hooks.
beforeEachandafterEachrun around every test,beforeAllandafterAllonce per file or block. Deepdescribenesting with sharedletvariables 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
expectcalls. - Parametrized tests.
it.eachruns 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.
toBecompares withObject.is: for primitives and the same reference.toEqualcompares structure recursively.toStrictEqualalso checksundefinedproperties, sparse arrays and class types.- Common matchers.
toContainfor an element in an array or a substring,toHaveLength,toMatchfor a regex,toBeCloseTofor floats,.notto invert any matcher.- Asymmetric matchers.
expect.objectContaining,expect.arrayContaining,expect.any(Number),expect.stringMatchingcheck 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 beforeexpectruns. - Promises.
- Make the test
asyncandawaitthe result, or useawait expect(promise).resolvesand.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 acatchwas 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,mockImplementationOncefor a single call. Check calls withtoHaveBeenCalledWith(...)andtoHaveBeenCalledTimes(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.
mockClearforgets calls,mockResetalso resets the implementation,mockRestoreadditionally returns the original method for a spy.clearMocksorrestoreMocksin 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, spreadawait 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()replacessetTimeout,setIntervalandDate.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 toIntlso the test passes on any machine.- Randomness.
- Mock
Math.randomorcrypto.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
setTimeoutnever resolves until you advance the timers. Restore real timers withvi.useRealTimers()inafterEach.
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
fetchor 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), thenserver.listen()inbeforeAll,server.resetHandlers()inafterEach,server.close()inafterAll.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;resetHandlersremoves 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.
getByRolewithnamefirst, thengetByLabelText,getByPlaceholderText,getByText,getByDisplayValue, andgetByTestIdlast, when nothing else fits. Role queries also check that the markup is accessible.- get, query, find.
getBythrows if there's no element,queryByreturnsnull(for checking absence),findByreturns a promise and waits up to 1 second. Each has anAllversion for lists.- Waiting.
findByisgetBypluswaitFor. InsidewaitForput one assertion and no side effects: the callback runs many times. To wait for a spinner to go away, usewaitForElementToBeRemoved.- user-event.
const user = userEvent.setup(), thenawait user.click(...)andawait user.type(input, "text"). It fires the full chain of events like a real user, unlike the single event offireEvent.- screen and within.
screensearches the whole document,within(row).getByText(...)only inside one element, such as a table row or dialog.- jest-dom matchers.
@testing-library/jest-domaddstoBeInTheDocument,toBeVisible,toBeDisabled,toBeChecked,toHaveValue,toHaveAccessibleName.screen.debug()prints the DOM,logRoleslists 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
QueryClientare rendered with awrapper, usually through your ownrenderWithProvidershelper. Create a newQueryClientwithretry: falsefor every test. - Hooks.
- A custom hook is tested through a component that uses it or with
renderHook, which returnsresult.currentandrerender. Don't mockuseStateor other React hooks: that tests React, not your code. - act().
- Makes sure state updates and effects are applied before assertions. Testing Library wraps
renderand events in it. The "not wrapped in act" warning usually means an update happened after the test finished: wait for it withfindBy. - Props, portals, errors.
rerender(<Price value={20} />)checks the reaction to new props. A modal in a portal is still found throughscreen. For error boundaries, silenceconsole.errorwith a spy during the test.- Suspense and RSC.
- With Suspense, check the fallback first, then
findBythe 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.
toMatchSnapshotsaves output and compares it later. Large snapshots get updated without reading and hide changes. SmalltoMatchInlineSnapshotvalues 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.
setupFilesin Vitest andsetupFilesAfterEnvin Jest run before each test file: jest-dom matchers, MSW server, global mocks.globals: truein Vitest makesdescribe,itandexpectavailable 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 dynamicimportgives a fresh copy. - Pools and projects.
- Vitest's
threadspool is faster,forksis more compatible with native modules.projectsruns different configs (jsdom for components, node for the server) in one run. - Coverage.
- Providers:
v8(fast, built into the engine) andistanbul. Branch coverage shows untakenifand?: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
waitForTimeoutisn't needed. Web-first assertions likeawait expect(locator).toBeVisible()retry until timeout, unlikeexpect(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 thanbeforeEach. - Login once.
- A setup project logs in and saves
storageStateto 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.clockcontrols time.routeFromHARreplays recorded traffic.- Debugging.
- The trace viewer shows each step with DOM snapshots, network and console.
codegenrecords actions into code.test.stepnames steps in reports,expect.softkeeps 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.webServerin the config starts the app before the tests.projectsrun 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.getdon't return elements: they are queued and run later. That's whyconst text = cy.get(...)doesn't work andasync/awaitdoesn'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")andcy.wait("@user")wait for a specific request instead of a fixedcy.wait(2000).interceptcan 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-cyor 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.
--ciin Jest doesn't write new snapshots,vitest --changedruns 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-axeor@axe-core/playwrightfinds 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.
toHaveScreenshotor 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-checkgenerates 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 beforeexpectruns. Pass a function:expect(() => fn()).toThrow().getByto check absence throws. UsequeryBywith.not.toBeInTheDocument().getByfor content that appears after loading fails at once. Useawait 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.mockis hoisted: its factory can't use variables from the test file withoutvi.hoisted.- Mocks not reset between tests leak calls and implementations into the next test. Turn on
clearMocksorrestoreMocks. toBeon objects compares references: two equal objects are nottoBeeach other. UsetoEqual.- Tests that check state, private methods or class names break on refactoring but miss real bugs.
- A
data-testidfor everything hides accessibility problems thatgetByRolewould catch. - Committed
it.onlysilently skips the rest of the file in CI.