encore-testing by encoredev/skills
npx skills add https://github.com/encoredev/skills --skill encore-testingEncore.ts 使用标准的 TypeScript 测试工具。推荐的配置是 Vitest。
npm install -D vitest
添加到 package.json:
{
"scripts": {
"test": "vitest"
}
}
// api.test.ts
import { describe, it, expect } from "vitest";
import { hello } from "./api";
describe("hello 端点", () => {
it("返回问候语", async () => {
const response = await hello();
expect(response.message).toBe("Hello, World!");
});
});
# 使用 Encore 运行(推荐 - 会设置基础设施)
encore test
# 或直接使用 npm 运行
npm test
推荐使用 encore test,因为它:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
// api.test.ts
import { describe, it, expect } from "vitest";
import { getUser } from "./api";
describe("getUser 端点", () => {
it("根据 ID 返回用户", async () => {
const user = await getUser({ id: "123" });
expect(user.id).toBe("123");
expect(user.name).toBeDefined();
});
});
Encore 提供隔离的测试数据库:
// user.test.ts
import { describe, it, expect, beforeEach } from "vitest";
import { createUser, getUser, db } from "./user";
describe("用户操作", () => {
beforeEach(async () => {
// 每个测试前清理数据
await db.exec`DELETE FROM users`;
});
it("创建并检索用户", async () => {
const created = await createUser({ email: "test@example.com", name: "Test" });
const retrieved = await getUser({ id: created.id });
expect(retrieved.email).toBe("test@example.com");
});
});
// order.test.ts
import { describe, it, expect } from "vitest";
import { createOrder } from "./order";
describe("订单服务", () => {
it("创建订单并通知用户服务", async () => {
// 服务调用在测试中正常工作
const order = await createOrder({
userId: "user-123",
items: [{ productId: "prod-1", quantity: 2 }],
});
expect(order.id).toBeDefined();
expect(order.status).toBe("pending");
});
});
import { describe, it, expect } from "vitest";
import { getUser } from "./api";
import { APIError } from "encore.dev/api";
describe("错误处理", () => {
it("对不存在的用户抛出 NotFound 错误", async () => {
await expect(getUser({ id: "nonexistent" }))
.rejects
.toThrow("user not found");
});
it("抛出正确的错误代码", async () => {
try {
await getUser({ id: "nonexistent" });
} catch (error) {
expect(error).toBeInstanceOf(APIError);
expect((error as APIError).code).toBe("not_found");
}
});
});
// notifications.test.ts
import { describe, it, expect, vi } from "vitest";
import { orderCreated } from "./events";
describe("发布/订阅", () => {
it("发布订单创建事件", async () => {
const messageId = await orderCreated.publish({
orderId: "order-123",
userId: "user-456",
total: 9999,
});
expect(messageId).toBeDefined();
});
});
测试底层函数,而不是定时任务计划:
// cleanup.test.ts
import { describe, it, expect } from "vitest";
import { cleanupExpiredSessions } from "./cleanup";
describe("清理任务", () => {
it("移除过期的会话", async () => {
// 首先创建一些过期的会话
await createExpiredSession();
// 直接调用端点
await cleanupExpiredSessions();
// 验证清理已发生
const remaining = await countSessions();
expect(remaining).toBe(0);
});
});
import { describe, it, expect, vi, beforeEach } from "vitest";
import { sendWelcomeEmail } from "./email";
// 模拟外部 API
vi.mock("./external-email-client", () => ({
send: vi.fn().mockResolvedValue({ success: true }),
}));
describe("电子邮件服务", () => {
it("发送欢迎邮件", async () => {
const result = await sendWelcomeEmail({ userId: "123" });
expect(result.sent).toBe(true);
});
});
创建 vite.config.ts(对于 ~encore 导入是必需的):
/// <reference types="vitest" />
import { defineConfig } from "vite";
import path from "path";
export default defineConfig({
resolve: {
alias: {
"~encore": path.resolve(__dirname, "./encore.gen"),
},
},
test: {
globals: true,
environment: "node",
include: ["**/*.test.ts"],
coverage: {
reporter: ["text", "json", "html"],
},
},
});
安装 Vitest 扩展 并添加到 .vscode/settings.json:
{
"vitest.commandLine": "encore test"
}
注意: 对于 VS Code 测试资源管理器,禁用文件级并行以避免端口冲突:
// vite.config.ts
export default defineConfig({
// ...
test: {
fileParallelism: false, // 为 VS Code 禁用
// ...
},
});
为 CI 重新启用:encore test --fileParallelism=true
encore test 运行测试并设置基础设施每周安装数
166
代码仓库
GitHub 星标数
20
首次出现
2026年1月21日
安全审计
安装于
codex132
opencode129
gemini-cli126
claude-code112
github-copilot108
cursor97
Encore.ts uses standard TypeScript testing tools. The recommended setup is Vitest.
npm install -D vitest
Add to package.json:
{
"scripts": {
"test": "vitest"
}
}
// api.test.ts
import { describe, it, expect } from "vitest";
import { hello } from "./api";
describe("hello endpoint", () => {
it("returns a greeting", async () => {
const response = await hello();
expect(response.message).toBe("Hello, World!");
});
});
# Run with Encore (recommended - sets up infrastructure)
encore test
# Or run directly with npm
npm test
Using encore test is recommended because it:
// api.test.ts
import { describe, it, expect } from "vitest";
import { getUser } from "./api";
describe("getUser endpoint", () => {
it("returns the user by ID", async () => {
const user = await getUser({ id: "123" });
expect(user.id).toBe("123");
expect(user.name).toBeDefined();
});
});
Encore provides isolated test databases:
// user.test.ts
import { describe, it, expect, beforeEach } from "vitest";
import { createUser, getUser, db } from "./user";
describe("user operations", () => {
beforeEach(async () => {
// Clean up before each test
await db.exec`DELETE FROM users`;
});
it("creates and retrieves a user", async () => {
const created = await createUser({ email: "test@example.com", name: "Test" });
const retrieved = await getUser({ id: created.id });
expect(retrieved.email).toBe("test@example.com");
});
});
// order.test.ts
import { describe, it, expect } from "vitest";
import { createOrder } from "./order";
describe("order service", () => {
it("creates an order and notifies user service", async () => {
// Service calls work normally in tests
const order = await createOrder({
userId: "user-123",
items: [{ productId: "prod-1", quantity: 2 }],
});
expect(order.id).toBeDefined();
expect(order.status).toBe("pending");
});
});
import { describe, it, expect } from "vitest";
import { getUser } from "./api";
import { APIError } from "encore.dev/api";
describe("error handling", () => {
it("throws NotFound for missing user", async () => {
await expect(getUser({ id: "nonexistent" }))
.rejects
.toThrow("user not found");
});
it("throws with correct error code", async () => {
try {
await getUser({ id: "nonexistent" });
} catch (error) {
expect(error).toBeInstanceOf(APIError);
expect((error as APIError).code).toBe("not_found");
}
});
});
// notifications.test.ts
import { describe, it, expect, vi } from "vitest";
import { orderCreated } from "./events";
describe("pub/sub", () => {
it("publishes order created event", async () => {
const messageId = await orderCreated.publish({
orderId: "order-123",
userId: "user-456",
total: 9999,
});
expect(messageId).toBeDefined();
});
});
Test the underlying function, not the cron schedule:
// cleanup.test.ts
import { describe, it, expect } from "vitest";
import { cleanupExpiredSessions } from "./cleanup";
describe("cleanup job", () => {
it("removes expired sessions", async () => {
// Create some expired sessions first
await createExpiredSession();
// Call the endpoint directly
await cleanupExpiredSessions();
// Verify cleanup happened
const remaining = await countSessions();
expect(remaining).toBe(0);
});
});
import { describe, it, expect, vi, beforeEach } from "vitest";
import { sendWelcomeEmail } from "./email";
// Mock external API
vi.mock("./external-email-client", () => ({
send: vi.fn().mockResolvedValue({ success: true }),
}));
describe("email service", () => {
it("sends welcome email", async () => {
const result = await sendWelcomeEmail({ userId: "123" });
expect(result.sent).toBe(true);
});
});
Create vite.config.ts (required for ~encore imports):
/// <reference types="vitest" />
import { defineConfig } from "vite";
import path from "path";
export default defineConfig({
resolve: {
alias: {
"~encore": path.resolve(__dirname, "./encore.gen"),
},
},
test: {
globals: true,
environment: "node",
include: ["**/*.test.ts"],
coverage: {
reporter: ["text", "json", "html"],
},
},
});
Install the Vitest extension and add to .vscode/settings.json:
{
"vitest.commandLine": "encore test"
}
Note: For VS Code test explorer, disable file-level parallelism to avoid port conflicts:
// vite.config.ts
export default defineConfig({
// ...
test: {
fileParallelism: false, // Disable for VS Code
// ...
},
});
Re-enable for CI: encore test --fileParallelism=true
encore test to run tests with infrastructure setupWeekly Installs
166
Repository
GitHub Stars
20
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex132
opencode129
gemini-cli126
claude-code112
github-copilot108
cursor97
Lark CLI IM 即时消息管理工具:机器人/用户身份操作聊天、消息、文件下载
34,600 周安装