上线与维护测试
测试
单元测试和 E2E 测试指南
测试策略
| 类型 | 工具 | 覆盖目标 |
|---|---|---|
| 源码冒烟 | Node.js test runner | 配置、路由挂载、关键文案和模板边界 |
| 包测试 | Vitest | workspace 包的纯函数、provider、服务层 |
| E2E 测试 | Playwright | 登录、受保护路由、核心用户流程 |
运行测试
# mono-web 源码冒烟
pnpm test
# workspace 包测试
cd ../..
pnpm test:packages
# E2E 测试
pnpm e2e
# CI 环境 E2E
pnpm e2e:ci源码冒烟
mono-web 当前的轻量测试放在 apps/mono-web/tests/*.test.mjs,用 Node.js 自带 test runner 跑。它们适合检查不会启动数据库和浏览器的基础约束,例如:
- 首页配置没有退回模板占位符
- i18n 关键文案存在
- 支付路由已经挂载
- 管理员或付费相关口子没有裸露给普通用户
编写示例
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
const source = await readFile(
new URL("../src/server/app.ts", import.meta.url),
"utf8",
);
test("payment routes are mounted", () => {
assert.match(source, /paymentsRouter/);
});包测试
workspace 包继续使用 Vitest。测试文件放在各自 package 的 test/ 或 tests/ 目录下。
E2E 测试
Playwright 测试覆盖核心用户流程:
import { test, expect } from "@playwright/test";
test("user can view events page", async ({ page }) => {
await page.goto("/events");
await expect(page.getByRole("heading", { name: /活动/ })).toBeVisible();
});运行单个测试文件
pnpm exec playwright test tests/events.spec.ts调试模式
pnpm exec playwright test --debug测试最佳实践
- 单元测试关注纯函数和业务逻辑
- E2E 测试关注用户可见的交互流程
- 使用
describe分组相关测试 - 测试命名描述预期行为(
should ...) - 避免测试实现细节,关注输入输出