Files
bun-app-template/tests/server/config.test.ts
2026-05-20 00:18:07 +08:00

96 lines
2.7 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import { rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { loadServerConfig, parseRuntimeArgs } from "../../src/server/config";
describe("parseRuntimeArgs", () => {
test("无参数返回空对象", () => {
const result = parseRuntimeArgs([]);
expect(result).toEqual({});
});
test("有参数返回 configPath", () => {
const result = parseRuntimeArgs(["config.yaml"]);
expect(result).toEqual({ configPath: "config.yaml" });
});
});
describe("loadServerConfig", () => {
test("无 configPath 使用默认值", async () => {
const config = await loadServerConfig();
expect(config.host).toBe("127.0.0.1");
expect(config.port).toBe(3000);
});
test("环境变量 HOST 覆盖默认值", async () => {
const prev = process.env["HOST"];
process.env["HOST"] = "0.0.0.0";
try {
const config = await loadServerConfig();
expect(config.host).toBe("0.0.0.0");
} finally {
if (prev === undefined) {
delete process.env["HOST"];
} else {
process.env["HOST"] = prev;
}
}
});
test("环境变量 PORT 覆盖默认值", async () => {
const prev = process.env["PORT"];
process.env["PORT"] = "8080";
try {
const config = await loadServerConfig();
expect(config.port).toBe(8080);
} finally {
if (prev === undefined) {
delete process.env["PORT"];
} else {
process.env["PORT"] = prev;
}
}
});
test("YAML 配置文件不存在时报错", async () => {
try {
await loadServerConfig("/nonexistent/path/config.yaml");
expect.unreachable();
} catch (error) {
expect((error as Error).message).toContain("配置文件不存在");
}
});
test("YAML 配置文件加载 server 配置", async () => {
const temp = tmpdir();
const yamlPath = join(temp, "test-config.yaml");
const yamlContent = 'server:\n host: "0.0.0.0"\n port: 9999\n';
await writeFile(yamlPath, yamlContent);
try {
const config = await loadServerConfig(yamlPath);
expect(config.host).toBe("0.0.0.0");
expect(config.port).toBe(9999);
} finally {
await rm(yamlPath, { force: true });
}
});
test("YAML 缺少 server 字段时使用默认值", async () => {
const temp = tmpdir();
const yamlPath = join(temp, "test-empty.yaml");
const yamlContent = "runtime:\n debug: true\n";
await writeFile(yamlPath, yamlContent);
try {
const config = await loadServerConfig(yamlPath);
expect(config.host).toBe("127.0.0.1");
expect(config.port).toBe(3000);
} finally {
await rm(yamlPath, { force: true });
}
});
});