javascript-testing-patterns
它能做什么
这份指南教你如何全面测试 JavaScript/TypeScript 代码。它会介绍如何搭建工具来测试小的代码单元(单元测试)、各部分如何协同工作(集成测试),以及最终用户如何与程序交互(端到端测试),还会讲解模拟数据(mocking)和测试驱动开发(TDD)等技巧。
适用场景
- ✓刚开始一个新项目,需要搭建测试环境时。
- ✓为某个函数或类编写测试时。
- ✓想确保代码的不同部分能良好配合工作时。
技能链接
https://github.com/wshobson/agents/blob/main/plugins/javascript-typescript/skills/javascript-testing-patterns/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“我该怎么用 Jest 为项目搭建测试?”
每周 5 个新技能,1 分钟读完。
工作原理
文中介绍了如何使用 Jest 和 Vitest 等常用工具。你可以编写测试,检查代码的每个部分是否按预期工作,必要时还可以模拟外部依赖。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
JavaScript Testing Patterns
Comprehensive guide for implementing robust testing strategies in JavaScript/TypeScript applications using modern testing frameworks and best practices.
When to Use This Skill
- Setting up test infrastructure for new projects
- Writing unit tests for functions and classes
- Creating integration tests for APIs and services
- Implementing end-to-end tests for user flows
- Mocking external dependencies and APIs
- Testing React, Vue, or other frontend components
- Implementing test-driven development (TDD)
- Setting up continuous testing in CI/CD pipelines
Testing Frameworks
Jest - Full-Featured Testing Framework
Setup:
// jest.config.ts
import type { Config } from "jest";
const config: Config = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["<rootDir>/src"],
testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"],
collectCoverageFrom: [
"src/**/*.ts",
"!src/**/*.d.ts",
"!src/**/*.interface.ts",
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
setupFilesAfterEnv: ["<rootDir>/src/test/setup.ts"],
};
export default config;
Vitest - Fast, Vite-Native Testing
Setup:
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
environment: "node",
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
exclude: ["**/*.d.ts", "**/*.config.ts", "**/dist/**"],
},
setupFiles: ["./src/test/setup.ts"],
},
});
Unit Testing Patterns
Pattern 1: Testing Pure Functions
// utils/calculator.ts
export function add(a: number, b: number): number {
return a + b;
}
export function divide(a: number, b: number): number {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}
// utils/calculator.test.ts
import { describe, it, expect } from "vitest";
import { add, divide } from "./calculator";
describe("Calculator", () => {
describe("add", () => {
it("should add two positive numbers", () => {
expect(add(2, 3)).toBe(5);
});
it("should add negative numbers", () => {
expect(add(-2, -3)).toBe(-5);
});
it("should handle zero", () => {
expect(add(0, 5)).toBe(5);
expect(add(5, 0)).toBe(5);
});
});
describe("divide", () => {
it("should divide two numbers", () => {
expect(divide(10, 2)).toBe(5);
});
it("should handle decimal results", () => {
expect(divide(5, 2)).toBe(2.5);
});
it("should throw error when dividing by zero", () => {
expect(() => divide(10, 0)).toThrow("Division by zero");
});
});
});
Pattern 2: Testing Classes
// services/user.service.ts
export class UserService {
private users: Map<string, User> = new Map();
create(user: User): User {
if (this.users.has(user.id)) {
throw new Error("User already exists");
}
this.users.set(user.id, user);
return user;
}
findById(id: string): User | undefined {
return this.users.get(id);
}
update(id: string, updates: Partial<User>): User {
const user = this.users.get(id);
if (!user) {
throw new Error("User not found");
}
const updated = { ...user, ...updates };
this.users.set(id, updated);
return updated;
}
delete(id: string): boolean {
return this.users.delete(id);
}
}
// services/user.service.test.ts
import { describe, it, expect, beforeEach } from "vitest";
import { UserService } from "./user.service";
describe("UserService", () => {
let service: UserService;
beforeEach(() => {
service = new UserService();
});
describe("create", () => {
it("should create a new user", () => {
const user = { id: "1", name: "John", email: "john@example.com" };
const created = service.create(user);
expect(created).toEqual(user);
expect(service.findById("1")).toEqual(user);
});
it("should throw error if user already exists", () => {
const user = { id: "1", name: "John", email: "john@example.com" };
service.create(user);
expect(() => service.create(user)).toThrow("User already exists");
});
});
describe("update", () => {
it("should update existing user", () => {
const user = { id: "1", name: "John", email: "john@example.com" };
…
常见问题
什么是单元测试?
单元测试用来检查代码中的小型独立部分,比如一个函数或一个类,确保它们做到了应该做的事情。
什么是 TDD(测试驱动开发)?
这是一种先写测试、再写实际代码的开发方式。测试一开始会失败,然后你只需编写刚好能让测试通过的代码。
什么是 mocking(模拟)?
模拟是指为代码的某些部分或外部服务创建假的(模拟的)版本。这样你就可以只测试某个特定部分,而不依赖其他部分的实际行为。
详情
作者的原始描述
Implement comprehensive testing strategies using Jest, Vitest, and Testing Library for unit tests, integration tests, and end-to-end testing with mocking, fixtures, and test-driven development. Use when writing JavaScript/TypeScript tests, setting up test infrastructure, or implementing TDD/BDD workflows.
repo: wshobson/agents
热度
- GitHub 星标
- 41k
- 排名
- #6712
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …