如何创建自定义Express请求配合Supertest测试?422错误排查
解决Supertest发送自定义Express请求时的422错误
你遇到的422错误是因为传给Supertest的请求体结构错误,后端无法识别groupName字段。下面是具体原因和修复方案:
问题原因
你的代码中把整个CreateGroupRequest对象(包含body嵌套字段)传给了Supertest的.send()方法,导致实际发送的请求体结构变成了:
{ "body": { "groupName": "xxx", "email": "xxx", "country": "US" } }
后端校验时会去req.body.groupName找值,但实际值在req.body.body.groupName,所以提示必填项缺失。
另外,CreateGroupRequest是用来给Express路由的req对象做类型提示的,不是用来构造Supertest请求体的。
修复方案
方案1:传递请求体的实际内容
直接把testCreateGroupRequest中的body字段传给.send():
await supertest(app) .post("/login") .send(testLoginBody) .expect(200) .then((response) => { sessionToken = response.body.token; }).then(() => { supertest(app) .post("/create_group") .set('X-JWT-Token', `${sessionToken}`) .send(testCreateGroupRequest.body) // 仅传递body部分 .then((response) => { console.log({ response }); }); });
方案2:简化请求体构造
不需要强转成Request类型,直接定义请求体对象即可:
// 直接构造请求体数据 const testCreateGroupBody = { groupName: testName, email: email, country: 'US', }; // 测试代码中使用该对象 await supertest(app) .post("/login") .send(testLoginBody) .expect(200) .then((response) => { sessionToken = response.body.token; }).then(() => { supertest(app) .post("/create_group") .set('X-JWT-Token', `${sessionToken}`) .send(testCreateGroupBody) .then((response) => { console.log({ response }); }); });
额外说明
CreateGroupRequest接口的作用是在Express路由处理函数中,给req对象提供类型提示,比如:
app.post('/create_group', (req: CreateGroupRequest, res) => { // 这里可以通过req.body.groupName获取类型提示 const { groupName, email, country } = req.body; // ...处理逻辑 });
而Supertest的.send()方法只需要接收请求体的原始数据,不需要符合Express的Request类型结构。
内容的提问来源于stack exchange,提问作者jt25
相关产品推荐
相关产品推荐

