Back to list
alexanderop

vitest-mocking

by alexanderop

9🍴 0📅 Jan 19, 2026

SKILL.md


name: vitest-mocking description: | Vitest mocking patterns and test double strategies. Use when writing tests that need mocks, spies, stubs, or fakes. Triggers include: mocking modules, stubbing globals (fetch, Date, timers), testing composables, mocking imports (default/named), creating test doubles, replacing dependencies, verifying mock calls, cleaning up mocks, or any question about "how do I mock X in Vitest". Also use when reviewing tests for proper mocking practices.

Vitest Mocking

Test Double Types

TypePurposeChanges Implementation?
SpyRecord calls, verify interactionsNo (uses real code)
MockReplace module entirelyYes
StubReturn canned responsesYes
FakeWorking but simplified implYes

Decision Guide

Use spy when: Verifying a function was called correctly while keeping real behavior

const fetchSpy = vi.spyOn(globalThis, "fetch");
await doSomething();
expect(fetchSpy).toHaveBeenCalledWith("https://api.example.com");

Use mock when: Replacing external dependencies (network, database, third-party modules)

vi.mock("./api-client");
vi.mocked(apiClient.fetch).mockResolvedValue({ data: "test" });

Use stubGlobal when: Replacing browser/Node globals

vi.stubGlobal("fetch", vi.fn().mockResolvedValue(mockResponse));

Essential Patterns

Mock Module (hoisted)

import { someFunc } from "./module";
vi.mock("./module"); // hoisted to top

it("test", () => {
  vi.mocked(someFunc).mockReturnValue("mocked");
});

Mock with Implementation

vi.mock("./module", () => ({
  someFunc: vi.fn().mockReturnValue("mocked"),
}));

Spy with Fake Return

const spy = vi.spyOn(obj, "method").mockReturnValue("fake");

Mock Global Fetch

globalThis.fetch = vi.fn().mockResolvedValue({
  ok: true,
  json: async () => ({ data: "test" }),
} as Response);

Fake Timers

beforeAll(() => vi.useFakeTimers());
afterAll(() => vi.useRealTimers());

it("test", async () => {
  // advance time
  await vi.advanceTimersByTimeAsync(5000);
});

Clean Up

beforeEach(() => vi.clearAllMocks()); // reset call counts
afterEach(() => vi.restoreAllMocks()); // restore originals

Reference

For complete examples including default imports, named imports, classes, partial mocks, snapshot testing, composables, and verification patterns, see references/cheat-sheet.md.

Score

Total Score

50/100

Based on repository quality metrics

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

0/10
説明文

100文字以上の説明がある

0/10
人気

GitHub Stars 100以上

0/15
最近の活動

3ヶ月以内に更新がある

0/10
フォーク

10回以上フォークされている

0/5
Issue管理

オープンIssueが50未満

+5
言語

プログラミング言語が設定されている

+5
タグ

1つ以上のタグが設定されている

0/5

Reviews

💬

Reviews coming soon