使用Jest+Supertest测试AWS Serverless API时遇500错误且无详情
问题分析与解决步骤
核心问题定位
你当前代码的关键错误是误用了Supertest的使用逻辑:你创建了一个本地空的express.Application实例,然后用它请求远程staging URL——但Supertest是用来测试本地Express应用的,并非用于发送HTTP请求到远程服务。这就是为什么无论传什么Token都返回500、且console.log输出异常的根本原因。
修复方案
方案1:改用axios测试远程接口
直接用标准HTTP请求库对接远程staging服务,更适合验收测试场景:
- 安装依赖:
npm install axios --save-dev
- 修改测试代码:
import axios from 'axios'; describe('Impersonate SE merchant', () => { const stagingUrl = 'full staging url string here'; const jwtToken = 'string I\'m putting in manually for now'; it('returns a valid access token', async () => { try { const response = await axios.get(stagingUrl, { headers: { 'Authorization': `Bearer ${jwtToken}` } }); console.log('响应内容:', response.data); expect(response.status).toEqual(200); } catch (error) { // 捕获并打印完整错误详情 console.error('请求错误状态:', error.response?.status); console.error('错误响应内容:', error.response?.data); throw error; // 抛出错误让测试标记为失败 } }); });
方案2:若测试本地Serverless离线服务(用Supertest)
如果是测试本地运行的serverless-offline服务,需连接本地服务地址而非空Express实例:
import { agent as request } from 'supertest'; describe('Impersonate SE merchant', () => { const localServerUrl = 'http://localhost:3000'; // 本地Serverless服务地址 const jwtToken = 'string I\'m putting in manually for now'; it('returns a valid access token', async () => { const response = await request(localServerUrl) .get('/your-api-path') // 仅填接口路径,无需完整URL .set('Authorization', `Bearer ${jwtToken}`); console.log('响应状态:', response.status); console.log('响应内容:', response.body); expect(response.status).toEqual(200); }); });
额外调试技巧
- 运行测试时加
--verbose参数,开启Jest详细日志,查看执行细节 - 在catch块中打印
error.stack,获取完整错误轨迹 - 对比Postman的请求头,确保测试代码的请求头(如Authorization、Content-Type)与Postman完全一致
内容的提问来源于stack exchange,提问作者rgorowsky
相关产品推荐
相关产品推荐

