如何使用SuperTest与Jest测试流式图片上传接口?
使用SuperTest测试
application/octet-stream图片上传端点 我来帮你搞定这个流式上传的测试用例!针对你的API端点(接收application/octet-stream类型请求),我们可以结合Node.js的文件流能力,用SuperTest轻松实现流式上传测试。下面是完整的实现方案和代码示例:
核心思路
借助Node.js的fs模块创建图片文件的可读流,通过SuperTest的.send()方法直接传递这个流,同时设置正确的Content-Type请求头,模拟真实的流式上传场景。
完整测试代码示例
import request from 'supertest'; import fs from 'fs'; import path from 'path'; // 确保app、ROOT_URL、endpoints这些变量已正确引入到测试文件中 const testImagePath = path.join(__dirname, '../../../assets/test_image.jpg'); const invalidFilePath = path.join(__dirname, '../../../assets/invalid_text_file.txt'); describe('Image Upload Endpoint', () => { // 测试:成功流式上传JPG图片 test('Successfully uploads JPG image via stream', async () => { // 创建图片文件的可读流 const imageStream = fs.createReadStream(testImagePath); const response = await request(app) .post(`${ROOT_URL}${endpoints.add_image.route}`) // 必须设置与API匹配的Content-Type .set('Content-Type', 'application/octet-stream') // 将可读流传递给SuperTest,内部会自动处理流式传输 .send(imageStream); // 根据你的API实际返回结果调整断言 expect(response.statusCode).toBe(200); expect(response.body).toHaveProperty('success', true); expect(response.body).toHaveProperty('imageId'); // 假设API返回图片ID }); // 测试:上传无效数据(非图片)时返回错误 test('Returns error for non-image stream', async () => { const invalidStream = fs.createReadStream(invalidFilePath); const response = await request(app) .post(`${ROOT_URL}${endpoints.add_image.route}`) .set('Content-Type', 'application/octet-stream') .send(invalidStream); expect(response.statusCode).toBe(400); // 假设API返回400状态码 expect(response.body).toHaveProperty('error', 'Invalid image data'); }); // 可选:测试空流场景 test('Returns error for empty stream', async () => { // 创建一个空的可读流 const emptyStream = fs.createReadStream(path.join(__dirname, '../../../assets/empty_file.txt')); const response = await request(app) .post(`${ROOT_URL}${endpoints.add_image.route}`) .set('Content-Type', 'application/octet-stream') .send(emptyStream); expect(response.statusCode).toBe(400); expect(response.body).toHaveProperty('error', 'Empty file received'); }); });
关键细节说明
- 文件流创建:用
fs.createReadStream()代替直接读取文件内容,避免大文件加载占用过多内存,更贴近真实的上传场景。 - 请求头设置:必须显式设置
Content-Type: application/octet-stream,否则服务器无法正确识别请求体类型。 - 测试覆盖:除了成功场景,别忘了覆盖异常情况(非图片数据、空流、权限问题等),保证测试的完整性。
- 路径处理:用
path.join()拼接文件路径,避免跨平台(Windows/Linux)的路径分隔符问题。
额外注意事项
如果你的API需要身份验证(比如Bearer Token),记得在请求中添加对应的请求头:
.set('Authorization', 'Bearer your-test-auth-token')
内容的提问来源于stack exchange,提问作者j_d
相关产品推荐
相关产品推荐

