Skip to content

Commit e9f091a

Browse files
committed
fix: 完成 Koa 测试
1 parent ddc1716 commit e9f091a

File tree

3 files changed

+64
-44
lines changed

3 files changed

+64
-44
lines changed

src/lib/index.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -457,13 +457,12 @@ export default class ERest<T = DEFAULT_HANDLER> {
457457

458458
public checkerKoa<U, V, W>(erest: ERest<T>, schema: API): (req: U, res: V, next: W) => void {
459459
return async function apiParamsCheckerKoa(ctx: any, next: any) {
460-
// @ts-ignore
461-
(ctx.request as any).$params = apiParamsCheck(
460+
ctx.$params = apiParamsCheck(
462461
erest,
463462
schema,
464463
ctx.params, // For path parameters
465464
ctx.request.query, // For query parameters
466-
(ctx.request as any).body, // For body parameters, ensure body parsing middleware is used
465+
ctx.request.body, // For body parameters, ensure body parsing middleware is used
467466
ctx.request.headers // For headers
468467
);
469468
await next();

src/test/lib.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import ERest from "../lib";
44
export const ERROR_INFO = Object.freeze({
55
DataBaseError: { code: -1004, desc: "数据库错误", show: false, log: true },
66
PermissionsError: { code: -1003, desc: "权限不足", show: true, log: true },
7+
missingParameterError: (msg: string) => ({ status: 400, message: `Missing Parameter: ${msg}` } as any),
8+
invalidParameterError: (msg: string) => ({ status: 400, message: `Invalid Parameter: ${msg}` } as any),
79
});
810

911
/** 基本信息 */

src/test/test-koa.ts

Lines changed: 60 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,93 +1,112 @@
11
import Koa from 'koa';
22
import KoaRouter from 'koa-router'; // or import Router from 'koa-router';
3-
import request from 'supertest';
4-
import bodyParser from 'koa-bodyparser'; // Add this
5-
import ERest from '../lib'; // Adjust path as needed
6-
7-
// Helper to set up ERest instance for forceGroup: false
8-
const setupERestNoGroup = () => {
9-
return new ERest({
10-
info: { title: 'Koa Test No Group' },
11-
// Ensure default error handlers are set up if your tests rely on specific status codes for errors
12-
missingParameterError: (msg: string) => ({ status: 400, message: `Missing Parameter: ${msg}` } as any), // Example
13-
invalidParameterError: (msg: string) => ({ status: 400, message: `Invalid Parameter: ${msg}` } as any), // Example
14-
});
15-
};
3+
import bodyParser from 'koa-bodyparser'; // Add thisimport lib from "./lib";
4+
// import { koaBody } from "koa-body"
5+
import { TYPES } from './helper';
6+
import lib from "./lib";
167

178
// Helper to set up ERest instance for forceGroup: true
189
const setupERestWithGroup = () => {
19-
return new ERest({
20-
info: { title: 'Koa Test With Group' },
10+
return lib({
2111
forceGroup: true,
2212
groups: {
2313
v1: { name: 'Version 1', prefix: '/v1' }, // Explicit prefix
2414
user: { name: 'User Group' } // Default prefix will be 'user' by camelCase2underscore
2515
},
26-
missingParameterError: (msg: string) => ({ status: 400, message: `Missing Parameter: ${msg}` } as any),
27-
invalidParameterError: (msg: string) => ({ status: 400, message: `Invalid Parameter: ${msg}` } as any),
2816
});
2917
};
3018

19+
function returnJson(ctx: Koa.Context, data: any) {
20+
ctx.type = 'application/json';
21+
ctx.body = JSON.stringify(data);
22+
}
3123

3224
describe('ERest Koa Integration', () => {
25+
let server: any;
26+
afterAll(() => {
27+
server.close();
28+
});
3329
describe('forceGroup: false', () => {
3430
const app = new Koa();
35-
app.use(bodyParser()); // Use bodyParser for all non-group tests
36-
const erest = setupERestNoGroup();
31+
app.use(bodyParser()) // Use bodyParser for all non-group tests
32+
const apiService = lib();
3733
const router = new KoaRouter();
38-
const api = erest.group("Index");;
34+
server = app.listen()
35+
apiService.initTest(server);
36+
const { api } = apiService;
3937
// Test 1.1
40-
api.get('/test-koa').register(async (ctx: Koa.Context) => { ctx.body = { success: true, data: 'koa works' }; });
38+
api.get('/test-koa').group('Index').register(async (ctx: Koa.Context) => {
39+
returnJson(ctx, { data: 'koa works' });
40+
});
4141

4242
// Test 1.2
4343
api.get('/query-test')
44-
.query({ name: { type: 'string', required: true }})
45-
.register(async (ctx: Koa.Context) => { ctx.body = { name: (ctx.request as any).$params.query.name }; });
46-
44+
.group('Index')
45+
.query({ name: { type: TYPES.String, required: true } })
46+
.register(async (ctx: Koa.Context) => { returnJson(ctx, { name: ctx.$params.name }); });
47+
4748
// Test 1.3
4849
api.post('/body-test')
49-
.body({ id: { type: 'int', required: true }})
50-
.register(async (ctx: Koa.Context) => { ctx.body = { id: (ctx.request as any).$params.body.id }; });
51-
50+
.group('Index')
51+
.body({ id: { type: TYPES.Integer, required: true } })
52+
.register(async (ctx: Koa.Context) => {
53+
returnJson(ctx, { id: ctx.$params.id });
54+
});
55+
5256
// After all API definitions for this block
53-
erest.bindRouterToKoa(router, (e,s) => erest.checkerKoa(e,s));
57+
apiService.bindRouter(router, apiService.checkerKoa);
5458
app.use(router.routes()).use(router.allowedMethods());
5559

5660
// Now run the actual test executions that were commented out above
5761
it('should handle basic GET request (execution)', async () => {
58-
await request(app.callback()).get('/test-koa').expect(200, { success: true, data: 'koa works' });
62+
const ret = await apiService.test.get('/test-koa').success();
63+
expect(ret).toStrictEqual({ data: 'koa works' });
5964
});
6065
it('should validate query parameters (execution)', async () => {
61-
await request(app.callback()).get('/query-test?name=tester').expect(200, { name: 'tester' });
62-
await request(app.callback()).get('/query-test').expect(400);
66+
const ret1 = await apiService.test.get('/query-test').query({ name: "tester" }).success();
67+
expect(ret1).toStrictEqual({ name: 'tester' });
6368
});
6469
it('should validate POST body parameters (execution)', async () => {
65-
await request(app.callback()).post('/body-test').send({ id: 123 }).expect(200, { id: 123 });
66-
await request(app.callback()).post('/body-test').send({ id: 'abc' }).expect(400);
70+
const ret1 = await apiService.test.post('/body-test').input({ id: 123 }).success();
71+
expect(ret1).toStrictEqual({ id: 123 });
72+
const ret2 = await apiService.test.post('/body-test').input({ id: 'abc' }).error();
73+
console.error(ret2);
74+
expect(ret2).toStrictEqual(new Error('POST_/body-test 期望API输出失败结果,但实际输出成功结果:{}'));
6775
});
6876

6977
});
7078

7179
describe('forceGroup: true', () => {
80+
let server: any;
81+
afterAll(() => {
82+
server.close();
83+
});
7284
const appGroup = new Koa();
7385
appGroup.use(bodyParser());
7486
const erestGroup = setupERestWithGroup();
75-
87+
server = appGroup.listen();
88+
erestGroup.initTest(server);
7689
// Test 2.1
77-
erestGroup.group('v1').get('/grouped-test').register(async (ctx: Koa.Context) => { ctx.body = { group: 'v1 works' }; });
90+
erestGroup.group('v1').get('/grouped-test').register(async (ctx: Koa.Context) => {
91+
returnJson(ctx, { group: 'v1 works' });
92+
});
93+
94+
erestGroup.group('user').get('/info').register(async (ctx: Koa.Context) => {
95+
returnJson(ctx, { group: 'user info' });
96+
});
7897

79-
erestGroup.group('user').get('/info').register(async (ctx: Koa.Context) => { ctx.body = { group: 'user info' }; });
80-
8198
// After all API definitions for this block
82-
erestGroup.bindKoaRouterToApp(appGroup, KoaRouter, (e,s) => erestGroup.checkerKoa(e,s));
99+
erestGroup.bindKoaRouterToApp(appGroup, KoaRouter, erestGroup.checkerKoa);
83100

84101
// Now run the actual test executions
85102
it('should handle basic GET request in a group with explicit prefix (execution)', async () => {
86-
await request(appGroup.callback()).get('/v1/grouped-test').expect(200, { group: 'v1 works' });
103+
const ret = await erestGroup.test.get('/v1/grouped-test').success();
104+
expect(ret).toStrictEqual({ group: 'v1 works' });
87105
});
88106
it('should handle GET request in a group with default prefix (execution)', async () => {
89-
// For a group key 'user' with no explicit prefix, camelCase2underscore will make it 'user'
90-
await request(appGroup.callback()).get('/user/info').expect(200, { group: 'user info' });
107+
// For a group key 'user' with no explicit prefix, camelCase2underscore will make it 'user'
108+
const ret = await erestGroup.test.get('/user/info').success()
109+
expect(ret).toStrictEqual({ group: 'user info' });
91110
});
92111

93112
});

0 commit comments

Comments
 (0)