Sub topic 13
Where Tests Live and What They Cover
This chapter assumes you know the feature-based layout from earlier chapters: feature folders with an index.ts public API, a shared/ folder, and the @/ path alias. It also assumes you have written tests with Vitest or Jest and React Testing Library. The examples use Vitest, but the placement rules are the same for Jest.
Why placement matters
Test files are code that has to be found, moved, and deleted along with the code they check. If tests sit in a top-level tests/ folder that mirrors src/, every rename or move touches two trees. Developers also stop noticing which files have no test. A test layout should follow the same rule as the rest of the structure: things that change together live together.
Colocate unit and component tests
Put a test file next to the file it tests and give it the same name plus .test. The spine's layout already shows this with CartList.tsx and CartList.test.tsx.
src/features/cart/
components/
CartList.tsx
CartList.test.tsx
hooks/
useCart.ts
useCart.test.ts
api.ts
api.test.ts
types.ts
index.tsColocation has three practical effects:
- Deleting a component removes its test in the same step.
- Relative imports in the test are short (
./CartList), and they don't cross a boundary. - A missing test is visible in the folder listing.
Keep one naming rule for the whole repository. *.test.ts(x) is the common choice. Don't mix it with *.spec.ts or __tests__ folders, because glob patterns for test runners, coverage, and lint overrides then need several entries.
What each kind of test covers
Colocation answers where a test goes. The next question is what it should exercise. Each layer has a different scope and a different thing you replace with a fake.
| Test kind | Lives in | Covers | Replace with fakes |
|---|---|---|---|
| Component | next to the component | rendering and user interaction for one component | callbacks, child features if heavy |
| Hook | next to the hook | state and effects, through `renderHook` | the feature's `api.ts` module |
| API module | next to `api.ts` | URL, parameters, error handling | `fetch` or a network mock |
| Feature integration | feature root, `*.integration.test.tsx` | a page-like flow across the feature's components, hooks, and API | the network only |
| Cross-feature or end-to-end | outside `src/` (for example `e2e/`) | whole user journeys in a real browser | nothing, or only third parties |
Write many fast tests at the top of the table and few slow ones at the bottom. Test behavior a user or a caller can observe, not the names of internal functions.
A component test
Here is the component and its type, followed by the test.
// src/features/cart/types.ts
export type CartItem = { id: string; name: string; quantity: number };// src/features/cart/components/CartList.tsx
import type { CartItem } from "../types";
type Props = { items: CartItem[]; onRemove: (id: string) => void };
export function CartList({ items, onRemove }: Props) {
if (items.length === 0) return <p>Your cart is empty.</p>;
return (
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name} x{item.quantity}
<button onClick={() => onRemove(item.id)}>Remove {item.name}</button>
</li>
))}
</ul>
);
}// src/features/cart/components/CartList.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { CartList } from "./CartList";
describe("CartList", () => {
it("shows a message when the cart is empty", () => {
render(<CartList items={[]} onRemove={() => {}} />);
expect(screen.getByText("Your cart is empty.")).toBeInTheDocument();
});
it("reports which item the user removed", async () => {
const onRemove = vi.fn();
render(
<CartList items={[{ id: "a1", name: "Mug", quantity: 2 }]} onRemove={onRemove} />
);
await userEvent.click(screen.getByRole("button", { name: "Remove Mug" }));
expect(onRemove).toHaveBeenCalledWith("a1");
});
});The test imports from ./CartList, not from the feature's index.ts. Inside a feature, tests may reach internal files, because they are part of the feature. The boundary rule applies to code outside it.
A hook test with a faked data layer
A hook that wraps api.ts is tested by replacing the API module. This keeps the test about the hook (query key, caching, returned shape) and not about HTTP.
// src/features/orders/hooks/useOrders.test.tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
import { fetchOrders } from "../api";
import { useOrders } from "./useOrders";
vi.mock("../api");
function createWrapper() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return function Wrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
};
}
describe("useOrders", () => {
it("loads orders for the given user", async () => {
vi.mocked(fetchOrders).mockResolvedValue([{ id: "o1", total: 20 }]);
const { result } = renderHook(() => useOrders("u1"), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(result.current.data).toEqual([{ id: "o1", total: 20 }]);
expect(fetchOrders).toHaveBeenCalledWith("u1");
});
});Set retry: false in test clients. With the default retries, a failing query stays in the loading state for several seconds, and your error-state tests time out.
Shared test utilities
Setup code that more than one feature needs belongs in src/shared/testing/. Do not copy it into each feature. Two files are usually enough: a setup file that the runner loads, and a render helper that adds providers.
// src/shared/testing/setup.ts
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(() => cleanup());// src/shared/testing/renderWithProviders.tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render } from "@testing-library/react";
import type { ReactElement } from "react";
import { MemoryRouter } from "react-router-dom";
export function renderWithProviders(ui: ReactElement, { route = "/" } = {}) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={client}>
<MemoryRouter initialEntries={[route]}>{ui}</MemoryRouter>
</QueryClientProvider>
);
}The explicit cleanup is needed because Vitest runs without global describe and afterEach by default, and Testing Library only registers automatic cleanup when those globals exist.
Connect the setup file and the @ alias in the runner config. Without the alias, a test that imports @/shared/testing/renderWithProviders fails to resolve even though the editor and tsc accept it.
// vitest.config.ts
import react from "@vitejs/plugin-react";
import path from "node:path";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [react()],
resolve: { alias: { "@": path.resolve(__dirname, "./src") } },
test: {
environment: "jsdom",
setupFiles: ["./src/shared/testing/setup.ts"],
include: ["src/**/*.test.{ts,tsx}"],
},
});Feature integration tests
An integration test renders a feature's top-level component with real hooks and a real api.ts, and replaces only the network. Mock Service Worker (MSW) is the usual tool, since it answers fetch calls with fixed responses. Name these files orders.integration.test.tsx at the feature root. The suffix lets you run them separately (vitest integration) and keeps the slow ones out of a quick watch loop.
Integration tests catch bugs that unit tests miss, such as a query key that two hooks spell differently. Write one for each main flow of a feature (load, empty, error, one mutation) and no more.
Tests and import boundaries
The no-restricted-imports rule from the previous chapter bans @/features/*/*, so a test in the cart feature that imports @/features/orders/hooks/useOrders is reported. That is correct. A test that needs another feature should use its public API (@/features/orders), or the test is revealing coupling that the production code also has. Relative imports inside the same feature, such as ./CartList, don't match the pattern and pass.
Common errors
- Testing implementation details. Asserting on state variables or internal helper calls breaks on refactors. Query by role and text, as
CartList.test.tsxdoes. - Shared mutable fixtures. A test that edits an imported fixture object changes it for every later test in the file. Build fixtures with small factory functions.
- One shared
QueryClient. Cached data leaks between tests, so results depend on test order. Create a client per test. - Test files in the production bundle. A bundler only includes files that are imported, so a stray
import "./x.test"is the real risk. Keep*.test.*out ofindex.tsand exclude them fromtscbuild configs if you emit declarations. - Mocking too much. If a component test mocks its hook, its API, and its child components, it checks only the mocks. Move that coverage to an integration test.
Exercise
A teammate adds src/tests/features/cart/CartList.test.tsx and imports @/features/cart/components/CartList. Name two problems with this placement and give the fix.
Show answer
First, the test lives far from its component, so moving or deleting CartList leaves the test behind and the two trees drift apart. Second, the import goes through @/features/cart/components/CartList, which the @/features/*/* restriction reports because it reaches into the feature's internals. Fix both by moving the file to src/features/cart/components/CartList.test.tsx and importing ./CartList. Relative imports inside a feature are allowed.
Exercise
Why does useOrders.test.tsx call vi.mock("../api") and a test client with retry: false?
Show answer
Mocking ../api keeps the test about the hook and removes the network from it. Setting retry: false makes a failed query report its error state immediately. With the default retries, an error-state test would wait several seconds and could time out.