测试¶
本指南介绍如何为 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/
生产产物门禁¶
使用以下命令运行权威生产构建:
NEXT_TELEMETRY_DISABLED=1 npm run build
构建使用 Webpack,并自动调用 npm run verify:standalone。校验器要求包含已编译的认证代理;如果 .next/standalone 中出现运行时数据库、活动环境文件、备份、应用源码、测试、文档或本地临时目录,构建将失败。新的运行时状态必须保留在 Docker 构建上下文之外。只有生产运行时确实需要某项资源时才放宽校验器,并应单独验证生成的 Docker 镜像。
最佳实践¶
将测试文件与源文件放在一起(例如
module.test.ts与module.ts相邻)为测试用例使用描述性名称,说明预期行为
测试边界情况 —— 空输入、null 值、边界条件
模拟外部依赖 —— API 调用、文件系统操作
保持测试聚焦 —— 每个测试应验证一个特定行为