Skip to content
DevFlash

By technology

Front-end automated testing: choosing and explaining your tests

A testing strategy based on interface risks, with interactions, asynchronous behavior and controlled dependencies.

  • 5 min read
  • 6 sections
  • Updated November 2, 2026

This guide is under editorial review.

In 1 minute

  • Choose the test level according to the rule and risk you need to verify.
  • Test observable actions and outcomes, using role and accessible name when appropriate.
  • Control asynchronous responses, concurrency and recovery without relying on fixed waits.

Front-end automated testing turns interface expectations into repeatable checks. In an interview, explain which failure each test detects and why its level is appropriate. A large test collection does not establish quality when it checks internal details but misses the flow people actually need to complete.

Start with risks: duplicated actions, stale responses, errors without recovery or inaccessible controls. Then choose test boundaries and data. This guide uses small examples to discuss strategy. For component behavior, combine it with the React questions; for keyboard access and names, use accessibility in interviews.

Planning front-end automated testing

Write an observable statement for each requirement. Instead of checking that a setter was called, verify that opening details makes information available. Instead of checking only an API call, verify what happens while it is pending and after failure. A useful selection connects each test to a consequence, not a specific implementation line.

  • List the main path and expected result.
  • Choose edges that change the rule, such as empty input or missing items.
  • Include a dependency failure and its recovery.
  • Define which data and clocks need control.
  • Avoid repeating the same case at every level without a reason.

When time is limited, prioritize the rule that can fail silently and the flow needed to use the delivery. State which checks remain. An honest strategy supports discussion of residual risk; promising complete coverage without defining it does not help the reviewer.

Unit, integration and end-to-end tests

A unit test isolates a small rule, such as calculating a price band. An integration test checks collaborating parts, such as a component, validation and a simulated network response. An end-to-end test follows a task in the running system, usually through a browser, across the boundaries the scenario uses. Define those boundaries because labels alone do not explain what is exercised.

Test deterministic rules close to their implementation with explicit inputs. Use integration checks for interactions and contracts between parts. Keep browser journeys for risks that depend on the real environment, such as navigation and focus behavior. Do not try to prove layout in a simulated DOM, or move every pure-function variation into browser tests merely to slow the suite down.

A test pyramid with many small dots at the base, fewer in the middle and a few at the top.
Test levels help distribute checks by behavior and risk; the figure does not prescribe mandatory proportions.

Interactions with Testing Library

  1. Find the control

    Query controls by role and accessible name when that reflects how they are found. Class selectors often couple tests to presentation.

  2. Model the interaction

    userEvent represents an interaction through a sequence of events, while dispatching one event can omit behavior.

  3. Await actions

    Create an instance with userEvent.setup() and await asynchronous actions so assertions do not run before the interaction finishes.

This self-contained example uses a details panel, distinct from the practice challenges. It assumes Vitest with a DOM environment and the testing libraries installed. Assertions check revealed content and the button's public state. If internals change while behavior stays the same, the test's intent remains valid.

import { useState } from "react";
import { expect, it } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
function Details() {
const [open, setOpen] = useState(false);
return <>
<button aria-expanded={open} onClick={() => setOpen(!open)}>
Details
</button>
{open && <p>Delivery takes two days.</p>}
</>;
}
it("reveals delivery details", async () => {
const user = userEvent.setup();
render(<Details />);
try {
await user.click(screen.getByRole("button", { name: "Details" }));
expect(screen.getByText("Delivery takes two days.")).not.toBeNull();
expect(screen.getByRole("button").getAttribute("aria-expanded")).toBe("true");
} finally { cleanup(); }
});

Initial absence may deserve an assertion when it is part of the rule. With several identically named controls, scope the region instead of arbitrarily selecting the first. When a role query fails, investigate whether the element exposes the expected semantics before switching to a less representative selector.

Loading, errors and asynchronous behavior

Control dependency resolution to observe intermediate states. An instant response can hide missing loading feedback or an invalid second action. Use findBy when an element should appear later and queryBy to check absence. waitFor is useful for a condition that requires retries; place an assertion that throws until the condition is satisfied.

Do

  • Perform the action once and await its consequence.
  • For concurrency, control two promises and resolve the newer one first. For errors, verify the message and subsequent attempt.

Avoid

  • Putting clicks inside a wait callback because it can run repeatedly.
  • Using fixed multi-second waits: they slow tests down and can still fail on a busy machine.

Mocks that preserve the real problem

Replace dependencies at boundaries you intend to control, such as transport or time. Mocking the hook whose logic you want to validate removes part of the subject under test. Simulated responses should respect the relevant contract shape, status and behavior. Do not return convenient objects that could never arrive from the real API.

Include empty responses, failures and unexpected data when those cases belong to the boundary. Typed fixtures help create consistent examples but do not replace input validation; see TypeScript and external data. Restore spies, handlers and mutable data between tests. A case that passes only after another suggests shared-state dependence.

Coverage, stability and maintenance

Coverage shows which code executed, not whether an assertion would catch a regression. Read each test and imagine an incorrect change: would it fail? If not, look for an expectation closer to the rule. Avoid huge snapshots that obscure important changes. A small test with a specific name makes the broken contract easier to understand.

When investigating flakiness, inspect real clocks, test ordering, external networks and incorrect waits before increasing timeouts. Understanding JavaScript promises helps explain these failures. At delivery, report the executed command, environment and unchecked areas. Separating evidence from intent makes review more objective.

Frequently asked questions

What should I test in a front-end component?

Test observable results, interactions, error states and relevant edges. Select cases by regression risk rather than checking only internal functions or reproducing every implementation detail.

How do unit, integration and end-to-end tests differ?

Unit tests isolate rules; integration tests exercise collaborating parts; end-to-end tests follow tasks in the running system. State your boundaries because projects may use labels differently.

How do I test API calls without relying on the network?

Control transport with simulated responses or inject a test dependency. Preserve the contract and cover delay, failure and success. Real integration may still need checking at another level.

Do I need 100% coverage in a take-home test?

Follow the stated criteria. Otherwise, prioritize risks and useful assertions while explaining gaps. Executing every line does not establish every behavior or guarantee that tests detect mistakes.

Practice with real tests

Solve front-end exercises in the browser, with the same tests a reviewer would run.

See the exercises