VitestAdvanced Techniques:Claude Code 实战指南
了解vitestadvanced techniques:Claude Code 实战. 包含实用技巧和代码示例。
Vitestで高品質な测试スイートを构建する
VitestはViteベースの高速测试框架です。Jest互換のAPIに加え、TypeScriptのネイティブサポート、HMR支持の監視モードなど、モダンな开发体験を提供します。Claude Code 複雑な测试シナリオのコード生成に非常に優れています。
高度なMock戦略
让 Claude Code模块Mockの设计を依頼吧。
> 外部API客户端のMockを设计して。
> 请求・响应の类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类型チェック付き、错误ケースも含めて。
import { describe, it, expect, vi, beforeEach } from "vitest";
import { UserService } from "./user-service";
import { ApiClient } from "./api-client";
// 模块Mock
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("ユーザー一覧を取得する", async () => {
const mockUsers = [
{ id: "1", name: "Alice", email: "[email protected]" },
{ id: "2", name: "Bob", email: "[email protected]" },
];
vi.mocked(mockClient.get).mockResolvedValue({ data: mockUsers });
const result = await service.getUsers();
expect(mockClient.get).toHaveBeenCalledWith("/users");
expect(result).toEqual(mockUsers);
});
it("APIエラー時にカスタム例外をスローする", async () => {
vi.mocked(mockClient.get).mockRejectedValue(
new Error("Network Error")
);
await expect(service.getUsers()).rejects.toThrow("ユーザーの取得に失敗しました");
});
});
参数测试(test.each)
同じロジックを複数の参数で验证するパターンです。
describe("バリデーション関数", () => {
it.each([
{ input: "[email protected]", expected: true },
{ input: "[email protected]", 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}
`(
"パスワード強度チェック: $password",
({ password, expected }) => {
expect(isStrongPassword(password)).toBe(expected);
}
);
});
カスタムマッチャーの创建
项目固有の断言を定義可以。
// 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,
};
},
});
// 类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类类型定義
declare module "vitest" {
interface Assertion<T = any> {
toBeWithinRange(floor: number, ceiling: number): void;
toBeValidDate(): void;
toMatchApiResponse(): void;
}
}
快照测试の活用
组件や数据構造の快照测试です。
import { render } from "@testing-library/react";
describe("UserProfile", () => {
it("プロフィールカードが正しくレンダリングされる", () => {
const { container } = render(
<UserProfile
user={{
id: "1",
name: "テストユーザー",
email: "[email protected]",
role: "admin",
}}
/>
);
expect(container).toMatchSnapshot();
});
it("インラインスナップショットでAPIレスポンスを検証", () => {
const response = transformUserResponse(rawData);
expect(response).toMatchInlineSnapshot(`
{
"displayName": "テストユーザー",
"email": "[email protected]",
"isAdmin": true,
}
`);
});
});
测试覆盖率の优化
// 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,
},
});
异步测试のパターン
タイマーや事件待機など、异步処理の测试手法です。
describe("非同期処理のテスト", () => {
it("デバウンス関数が正しく動作する", 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);
});
});
总结
Vitestは高速な実行速度とモダンなAPIにより、测试开发の体験を大きく向上させます。Claude Codeを活用すれば、Mock设计、参数测试、カスタムマッチャーなどの高度な测试パターンも快速实现是可能的。
E2E 测试の实现はPlaywright E2E 测试実践指南を、APIMock的详细信息请参阅MSW APIMock活用指南。Vitest官方文档也建议确认一下。
#Claude Code
#Vitest
#testing
#TypeScript
#quality assurance
Related Posts
Advanced
Advanced
Claude Code Hooks 完全指南:自动格式化、自动测试等实用配置
详解如何通过 Claude Code Hooks 实现自动格式化和自动测试。包含实际配置示例和真实使用场景。
Advanced
Advanced
Claude Code MCP Server 配置指南与实战用例
全面介绍 Claude Code 的 MCP Server 功能。从外部工具连接、服务器配置到真实集成案例,一文掌握 MCP 生态。
Advanced
Advanced
CLAUDE.md 编写完全指南:项目配置最佳实践
深入讲解如何编写高效的 CLAUDE.md 文件。学会向 Claude Code 传达你的技术栈、规范和项目结构,最大化输出质量。