在数据库应用中,编写测试最怕的就是“污染”真实数据。在 Bun + Turso + Drizzle 的体系下,最佳实践是利用 SQLite 的内存模式(In-memory) 进行单元测试,以及利用 Turso 的临时组(Groups) 进行集成测试。 以下是使用 bun:test 进行自动化测试的最佳实践:

  1. 单元测试:使用内存数据库 这种方式速度极快,不需要联网,且每个测试用例运行完后数据库会自动销毁,非常干净。 创建测试文件 src/index.test.ts: import { describe, expect, it, beforeAll } from “bun:test”; import { drizzle } from “drizzle-orm/libsql”; import { createClient } from “@libsql/client”; import { users } from ”./db/schema”; import * as schema from ”./db/schema”;

describe(“User Model Unit Tests”, () => { let db: any;

beforeAll(() => { // 使用内存模式初始化客户端,不连接远程 Turso const client = createClient({ url: “libsql://:memory:” }); db = drizzle(client, { schema }); });

it(“应该能成功创建一个用户”, async () => { const newUser = { name: “Test User”, email: “test@example.com” }; await db.insert(users).values(newUser);

const result = await db.query.users.findFirst();
expect(result).toBeDefined();
expect(result?.name).toBe("Test User");

});

it(“重复的 Email 应该报错”, async () => { const user = { name: “User1”, email: “same@example.com” }; await db.insert(users).values(user);

// 预期会抛出约束错误
expect(db.insert(users).values(user)).rejects.toThrow();

}); });

  1. 集成测试:测试 API 路由 Elysia 提供了一个非常方便的 .handle() 方法,让你可以在不真正启动网络端口的情况下,直接模拟请求。 import { describe, expect, it } from “bun:test”; import { app } from ”./index”; // 导入你的 Elysia 实例

describe(“Elysia API Integration”, () => { it(“GET /api/v1/users 应该返回 200”, async () => { const response = await app.handle( new Request(“http://localhost/api/v1/users”) );

expect(response.status).toBe(200);
const data = await response.json();
expect(Array.isArray(data)).toBe(true);

});

it(“POST 无效数据应返回 400”, async () => { const response = await app.handle( new Request(“http://localhost/api/v1/users”, { method: “POST”, headers: { “Content-Type”: “application/json” }, body: JSON.stringify({ name: “Only Name” }) // 缺少 email }) );

expect(response.status).toBe(400);

}); });

  1. 测试最佳实践建议
  • 运行测试命令: 在 package.json 中添加: “scripts”: { “test”: “bun test”, “test:watch”: “bun test —watch” }

    使用 bun test —watch 可以在你修改代码时立即看到测试结果,反馈极其迅速。

  • 环境隔离: 在测试文件中,通过 process.env.NODE_ENV === ‘test’ 来切换不同的数据库连接配置。

  • Mocking(模拟): 如果你有发送邮件或调用第三方支付的操作,可以使用 bun:test 的 mock 功能: import { mock } from “bun:test”; const sendEmail = mock(() => Promise.resolve(true));

🏁 总结你的 Bun + TypeScript 技能版图 你现在已经掌握了:

  • 运行时: Bun (原生支持 TS,极致速度)。
  • Web 框架: ElysiaJS (端到端类型安全)。
  • 数据库: Turso (边缘优先的分布式 SQLite)。
  • ORM: Drizzle (极简、高性能)。
  • 测试: bun:test (内置、兼容 Jest)。 最后的小贴士: Bun 更新非常快(几乎每周都有新版本)。建议养成定期执行 bun upgrade 的习惯,以获取最新的性能优化和功能修复。 如果你在实际搭建过程中遇到具体的报错或复杂的业务场景(比如权限校验、文件上传等),欢迎随时回来提问!祝你 Bun 开发愉快!🚀