Playwright E2E, Vitest, React Testing Library - E2E for user flows, unit tests for pure functions only, network-level API mocking - inverted testing pyramid prioritizing E2E tests
Quick Guide: Vitest runs tests through the same transform pipeline and config the app is built with, so aliases, plugins and TypeScript work without a second toolchain.
describe/it/expectfor structure,vi.fn()andvi.spyOn()for test doubles,vi.mock()for whole modules, andvi.useFakeTimers()for anything clock-driven. Vitest 4 is current stable (Vite 6+, Node 20+) and changed several mock defaults —vi.restoreAllMocks()no longer resets automocks, andpoolOptionsis gone.
Detailed Resources:
environment: "node", no setup file; follow
examples/core.md.document or window — set environment: "jsdom" (or happy-dom) and a
setup file; follow examples/integration.md.projects entry each, so a
single run covers all of them; see reference.md.<critical_requirements>
Pass test options as the second argument — test("name", { timeout: 10_000 }, () => {}). The
trailing-options form was removed after v2, and mixing an options object with a trailing timeout is
rejected outright.
Return every export the file under test imports from a vi.mock() factory. The factory
replaces the whole module, so anything it omits is undefined at import time; reach for
importOriginal() to keep the rest, and remember the call is hoisted above every import in the file.
Reset mock state between tests — restoreMocks: true in config, or an explicit
vi.resetAllMocks() in afterEach. In v4 vi.restoreAllMocks() touches only manual spies, so
automocked modules keep their state without it.
Mock at the boundary the code crosses. A module mock binds the test to the import graph and breaks on any refactor that moves a function; intercepting HTTP leaves the import graph free and exercises serialisation.
</critical_requirements>
Auto-detection: Vitest, vitest.config, vi.fn, vi.mock, vi.spyOn, vi.hoisted, vi.mockObject, vi.useFakeTimers, vi.advanceTimersByTime, mockResolvedValue, mockRejectedValue, importOriginal, toMatchInlineSnapshot, expect.schemaMatching, defineConfig test block, projects, coverage provider
Applies to:
projects, coverageHandled elsewhere:
Vitest reads the project's own Vite config, so a test resolves imports, aliases and plugins exactly as the application does. That is the whole reason it needs so little configuration of its own — and the reason a failure is usually a config question ("which environment is this suite running in?") rather than a runner question.
</philosophy><decision_framework>
Which kind of test double:
vi.spyOn(obj, "method"), which
keeps the original for restore.vi.fn() with mockReturnValue / mockResolvedValue; no module
machinery needed.vi.mock() for
the module, vi.useFakeTimers() for the clock, vi.stubGlobal() for a global.</decision_framework>
Options are the second argument. test.each covers table-driven cases without a loop, and
it.concurrent runs siblings in parallel inside one file.
describe("formatCurrency", () => {
it("formats the default currency", () => {
expect(formatCurrency(1234.56)).toBe("$1,234.56");
});
it("retries a known-flaky path", { retry: 2, timeout: 10_000 }, async () => {
await expect(fetchRate()).resolves.toBeGreaterThan(0);
});
it.each([
[0, "$0.00"],
[-1, "-$1.00"],
])("formats %d as %s", (input, expected) => {
expect(formatCurrency(input)).toBe(expected);
});
});
Full code: examples/core.md
vi.fn() creates a standalone double; vi.spyOn() wraps an existing method and can be restored.
Both record calls on .mock.
const onSave = vi.fn().mockResolvedValue({ id: "1" });
await submit({ onSave });
expect(onSave).toHaveBeenCalledWith({ title: "Draft" });
const spy = vi.spyOn(clock, "now").mockReturnValue(0);
stampEvent("saved");
expect(spy).toHaveBeenCalledTimes(1);
spy.mockRestore();
Full code: examples/core.md
vi.mock() is hoisted above the imports, so its factory sees nothing from the file body unless the
value comes from vi.hoisted(). importOriginal keeps the exports the test does not replace.
const { readConfig } = vi.hoisted(() => ({ readConfig: vi.fn() }));
vi.mock("./config", async (importOriginal) => ({
...(await importOriginal<typeof import("./config")>()),
readConfig,
}));
readConfig.mockReturnValue({ locale: "en-US" });
Full code: examples/core.md
Install fake timers, advance them explicitly, and return to real timers afterwards so later suites are unaffected.
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it("fires the debounced callback once", () => {
const onIdle = vi.fn();
watchIdle(onIdle, 300);
vi.advanceTimersByTime(300);
expect(onIdle).toHaveBeenCalledOnce();
});
Full code: examples/core.md
toStrictEqual compares shape as well as value; resolves / rejects keep async assertions in one
expression; inline snapshots keep the expected value beside the test.
await expect(loadUser("missing")).rejects.toThrowError(/not found/);
expect(toSummary(order)).toStrictEqual({ total: 118, items: 2 });
expect(parseArgs(["--json"]).json).toMatchInlineSnapshot(`true`);
Full code: examples/core.md
The test block lives in the project's own config file. environment decides what globals a suite
gets, setupFiles runs before each test file, and projects gives one run several of each.
import { defineConfig } from "vitest/config"; // not "vite" — that one has no `test` key
export default defineConfig({
test: {
environment: "node",
setupFiles: ["./tests/setup.ts"],
restoreMocks: true,
coverage: { provider: "v8", include: ["src/**/*.ts"] },
},
});
Full code: examples/integration.md — lookup table in reference.md
</patterns><red_flags>
Breaks at runtime:
test("x", fn, { retry: 2 }) — removed after v2; put them
in the second argument.vi.mock() factory referencing a const from the file body — the call is hoisted, so the
binding is in its temporal dead zone; take the value from vi.hoisted().await importOriginal() first.default key — the factory's return shape is the module's
shape, so default: vi.fn() is required.poolOptions in a v4 config — removed; maxWorkers and isolate are top-level.coverage.all in a v4 config — removed; coverage.include is now required for anything to be
reported.Surprising behaviour:
vi.restoreAllMocks() in v4 restores manual spies only; automocked modules need
vi.resetAllMocks().vi.fn().mock.invocationCallOrder starts at 1 in v4, where it started at 0 before.vi.fn().getMockName() answers "vi.fn()" rather than "spy", which changes snapshots that
captured it.undefined instead of calling the original.useFakeTimers() with useRealTimers().</red_flags>
npx skills add agents-inc/web-testing-vitest下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer