Claude Code के साथ VitestAdvanced Techniques
Claude Code का उपयोग करके vitestadvanced techniques सीखें। Practical tips और code examples शामिल हैं।
Vitestで高品質なtestスイート buildする
VitestはViteベースのfasttestframework है।Jest互換のAPIに加え、TypeScriptのネイティブサポート、HMRsupportの監視モード आदि、モダンなdevelopment体験を提供し है।Claude Codeはcomplexなtestシナリオのcodegenerateに非常に優れてい है।
高度なモック戦略
Claude Codeにmoduleモックの設計を依頼 करें।
> बाहर部APIclientのモックを設計して。
> request・responseのtype check付き、errorケースも含めて。
import { describe, it, expect, vi, beforeEach } from "vitest";
import { UserService } from "./user-service";
import { ApiClient } from "./api-client";
// moduleモック
vi.mock("./api-client", () => ({
ApiClient: vi.fn().mockImplementation(() => ({
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
})),
}));
describe("UserService", () => {
let service: UserService;
let mockClient: ReturnType<typeof vi.mocked<ApiClient>>;
beforeEach(() => {
vi.clearAllMocks();
mockClient = new ApiClient() as any;
service = new UserService(mockClient);
});
it("userlist fetchする", async () => {
const mockUsers = [
{ id: "1", name: "Alice", email: "alice@example.com" },
{ id: "2", name: "Bob", email: "bob@example.com" },
];
vi.mocked(mockClient.get).mockResolvedValue({ data: mockUsers });
const result = await service.getUsers();
expect(mockClient.get).toHaveBeenCalledWith("/users");
expect(result).toEqual(mockUsers);
});
it("APIerror時にカスタム例बाहरをスローする", async () => {
vi.mocked(mockClient.get).mockRejectedValue(
new Error("Network Error")
);
await expect(service.getUsers()).rejects.toThrow("userのfetchに失敗しました");
});
});
parametertest(test.each)
sameロジックを複数のparameterで検証するpattern है।
describe("validationfunction", () => {
it.each([
{ input: "test@example.com", expected: true },
{ input: "user+tag@domain.co.jp", expected: true },
{ input: "invalid-email", expected: false },
{ input: "@no-local.com", expected: false },
{ input: "no-domain@", expected: false },
{ input: "", expected: false },
])("isValidEmail($input) => $expected", ({ input, expected }) => {
expect(isValidEmail(input)).toBe(expected);
});
it.each`
password | minLength | hasUpper | hasNumber | expected
${"Abc12345"} | ${8} | ${true} | ${true} | ${true}
${"abc12345"} | ${8} | ${false} | ${true} | ${false}
${"short"} | ${8} | ${false} | ${false} | ${false}
${"NoNumbers"} | ${8} | ${true} | ${false} | ${false}
`(
"pathワード強度check: $password",
({ password, expected }) => {
expect(isStrongPassword(password)).toBe(expected);
}
);
});
カスタムマッチャーのcreate
Project固有のアサーションを定義でき है।
// vitest.setup.ts
import { expect } from "vitest";
expect.extend({
toBeWithinRange(received: number, floor: number, ceiling: number) {
const pass = received >= floor && received <= ceiling;
return {
message: () =>
`expected ${received} to be within range ${floor} - ${ceiling}`,
pass,
};
},
toBeValidDate(received: string) {
const date = new Date(received);
const pass = !isNaN(date.getTime());
return {
message: () => `expected "${received}" to be a valid date string`,
pass,
};
},
toMatchApiResponse(received: unknown) {
const pass =
typeof received === "object" &&
received !== null &&
"data" in received &&
"meta" in received;
return {
message: () => `expected value to match API response shape`,
pass,
};
},
});
// type definitions
declare module "vitest" {
interface Assertion<T = any> {
toBeWithinRange(floor: number, ceiling: number): void;
toBeValidDate(): void;
toMatchApiResponse(): void;
}
}
スナップショットtestのutilization
componentやdata構造のスナップショットtest है।
import { render } from "@testing-library/react";
describe("UserProfile", () => {
it("プロフィールcardが正しくレンダリングされる", () => {
const { container } = render(
<UserProfile
user={{
id: "1",
name: "testuser",
email: "test@example.com",
role: "admin",
}}
/>
);
expect(container).toMatchSnapshot();
});
it("インラインスナップショットでAPIresponseを検証", () => {
const response = transformUserResponse(rawData);
expect(response).toMatchInlineSnapshot(`
{
"displayName": "testuser",
"email": "test@example.com",
"isAdmin": true,
}
`);
});
});
testカバレッジのoptimization
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
coverage: {
provider: "v8",
reporter: ["text", "json", "html", "lcov"],
include: ["src/**/*.{ts,tsx}"],
exclude: [
"src/**/*.d.ts",
"src/**/*.test.{ts,tsx}",
"src/**/*.stories.{ts,tsx}",
"src/types/**",
"src/**/index.ts",
],
thresholds: {
statements: 80,
branches: 75,
functions: 80,
lines: 80,
},
},
setupFiles: ["./vitest.setup.ts"],
environment: "jsdom",
globals: true,
},
});
asynctestのpattern
タイマーやevent待機 आदि、asyncprocessingのtest手法 है।
describe("asyncprocessingのtest", () => {
it("デバウンスfunctionが正しく動作する", async () => {
vi.useFakeTimers();
const fn = vi.fn();
const debounced = debounce(fn, 300);
debounced("a");
debounced("b");
debounced("c");
expect(fn).not.toHaveBeenCalled();
vi.advanceTimersByTime(300);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith("c");
vi.useRealTimers();
});
it("リトライロジックが正しく動作する", async () => {
const fn = vi
.fn()
.mockRejectedValueOnce(new Error("1回目失敗"))
.mockRejectedValueOnce(new Error("2回目失敗"))
.mockResolvedValue("成功");
const result = await retry(fn, { maxAttempts: 3, delay: 100 });
expect(result).toBe("成功");
expect(fn).toHaveBeenCalledTimes(3);
});
});
Summary
Vitestはfastな実行速度とモダンなAPI से、testdevelopmentの体験を大きく向ऊपरさせ है।Claude Code का लाभ उठाकर、モック設計、parametertest、カスタムマッチャー आदिの高度なtestpatternも素早くimplementationpossible है।
E2EtestのimplementationはPlaywright E2Etest実践ガイドを、APIモックके details के लिएMSW APIモックutilizationガイドをदेखें。Vitestofficial documentationもconfirmしておきましょう。
अपने Claude Code वर्कफ़्लो को अगले स्तर पर ले जाएँ
Claude Code में तुरंत कॉपी-पेस्ट करने योग्य 50 आज़माए हुए प्रॉम्प्ट टेम्पलेट।
मुफ़्त PDF: 5 मिनट में Claude Code चीटशीट
मुख्य कमांड, शॉर्टकट और प्रॉम्प्ट उदाहरण एक प्रिंट योग्य पृष्ठ पर।
लेखक के बारे में
Masa
Claude Code का गहराई से उपयोग करने वाले इंजीनियर। claudecode-lab.com चलाते हैं, जो 10 भाषाओं में 2,000 से अधिक पेजों वाला टेक मीडिया है।
संबंधित लेख
Claude Code Agent SDK का परिचय — स्वायत्त एजेंट तेज़ी से बनाएं
Claude Code Agent SDK से स्वायत्त AI एजेंट बनाना सीखें। सेटअप, टूल परिभाषा और मल्टी-स्टेप निष्पादन को व्यावहारिक कोड उदाहरणों के साथ समझें।
Claude Code में कॉन्टेक्स्ट प्रबंधन तकनीकों की संपूर्ण गाइड
Claude Code की कॉन्टेक्स्ट विंडो को अधिकतम रूप से उपयोग करने की व्यावहारिक तकनीकें। टोकन अनुकूलन, वार्तालाप विभाजन और CLAUDE.md का उपयोग।
Claude Code Hooks में Mastery: Auto-Format, Auto-Test, और बहुत कुछ
Claude Code hooks से auto-formatting और auto-testing setup करना सीखें। Practical configuration examples और real-world use cases शामिल हैं।