从头开始创建一个自动产生文档/类型安全的现代API(12) 单元测试

下面我们给 API 添加单元测试。

安装vitest

安装:

1
bun add -D vitest

配置 VITEST

添加文件 vitest.config.ts:

1
2
3
4
5
6
7
8
9
10
import path from "node:path";
import { defineConfig } from "vitest/config";

export default defineConfig({
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});

编写第一个测试脚本

添加文件 app/api/[[...route]]/routes/tasks/tasks.test.ts:

1
2
3
4
5
6
7
8
9
10
11
12
import { describe, expect, it } from "vitest";

import router from "./tasks.index";

describe("Task List", () => {
it("responds with an array", async() =>{
const responds = await router.request("/list");
const result = await responds.text();
console.log(result);
expect(false).toBe(true);
});
});

运行:

1
bun run test

可以看到以下执行结果:

修正错误,第一次通过测试

修改 app/api/[[...route]]/lib/create-app.ts:

1
2
3
4
5
6
...
export function createTestApp(router: AppOpenAPI) {
const testApp = createApp();
testApp.route("/",router);
return testApp;
}

修改 app/api/[[...route]]/routes/tasks/tasks.test.ts:

1
2
3
4
5
6
7
8
9
10
11
...
describe("Task List", () => {
it("responds with an array", async() =>{
const testRouter = createTestApp(router);
const responds = await testRouter.request("/api/tasks");
const result = await responds.json();
console.log(result);
// @ts-expect-error
expectTypeOf(result).toBeArray();
});
});

再次测试,测试通过:

采用 Hono 提供的 testclient 测试

修改 app/api/[[...route]]/routes/tasks/tasks.test.ts:

1
2
3
4
5
6
7
8
9
10
...
describe("Task List", () => {
it("responds with an array again", async() =>{
const client = testClient(createApp().route("/",router));
const response = await client.api.tasks.$get();
const json = await response.json();

expectTypeOf(json).toBeArray();
});
});

可以看到,用 clientTest 更方便。再次测试,测试通过。

测试时关闭log

可以在跑测试时将 LOG LEVEL 设置为 silent, 修改package.json:

1
2
3
...
"test": "LOG_LEVEL=silent vitest"
...

同时添加这个等级到 env.ts:

1
2
3
...
LOG_LEVEL: z.enum(["fatal","error","warn", "info", "debug","trace","silent"]),
...

再次运行测试,可以发现日志不出现了。


作者:Bearalise
出处:从头开始创建一个自动产生文档/类型安全的现代API(12) 单元测试
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明,必须在文章中给出原文链接。

请我喝杯咖啡吧~

支付宝
微信