测试¶
本指南介绍如何为 InnoClaw 编写和运行测试。
测试框架¶
InnoClaw 使用 Vitest(v4+)作为测试框架,配置在 vitest.config.ts 中。
配置¶
// vitest.config.ts
import { defineConfig } from "vitest/config";
import path from "path";
export default defineConfig({
test: {
// Test file patterns
include: ["src/**/*.test.{ts,tsx}"],
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
运行测试¶
# Run all tests
npm test
# Run tests with Vitest directly
npx vitest run
# Run tests in watch mode (re-runs on file changes)
npx vitest
# Run a specific test file
npx vitest run src/lib/rag/chunker.test.ts
# Run tests matching a pattern
npx vitest run --grep "should chunk text"
编写测试¶
测试文件位置¶
测试文件应与它们测试的源文件放在一起:
src/
├── lib/
│ ├── rag/
│ │ ├── chunker.ts
│ │ └── chunker.test.ts # Tests for chunker.ts
│ └── utils/
│ ├── helpers.ts
│ └── helpers.test.ts # Tests for helpers.ts
测试结构¶
import { describe, it, expect } from "vitest";
import { myFunction } from "./my-module";
describe("myFunction", () => {
it("should return expected result", () => {
const result = myFunction("input");
expect(result).toBe("expected output");
});
it("should handle edge cases", () => {
expect(myFunction("")).toBe("");
expect(myFunction(null)).toBeNull();
});
});
路径别名¶
使用 @/ 别名从 src/ 目录导入:
import { someUtil } from "@/lib/utils/helpers";
测试分类¶
单元测试¶
独立测试单个函数和模块:
npx vitest run src/lib/rag/
集成测试¶
测试模块之间的交互(例如 API 路由与数据库):
npx vitest run src/app/api/
最佳实践¶
将测试文件与源文件放在一起(例如
module.test.ts与module.ts相邻)为测试用例使用描述性名称,说明预期行为
测试边界情况 —— 空输入、null 值、边界条件
模拟外部依赖 —— API 调用、文件系统操作
保持测试聚焦 —— 每个测试应验证一个特定行为