如何在NestJS Jest单元测试中覆盖FileInterceptor代码?
测试覆盖NestJS FileInterceptor配置代码的方法
要覆盖你控制器中FileInterceptor的配置代码,需要在测试用例中模拟携带文件的multipart请求,具体操作如下:
1. 核心操作:发送带文件的请求
你的FileInterceptor指定了接收名为file的文件字段,测试时需通过multipart/form-data格式传入该字段,触发拦截器逻辑。
使用supertest的示例代码:
import { Test } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import * as request from 'supertest'; import { YourController } from './your.controller'; import { YourModule } from './your.module'; describe('YourController', () => { let app: INestApplication; beforeEach(async () => { const moduleFixture = await Test.createTestingModule({ imports: [YourModule], }).compile(); app = moduleFixture.createNestApplication(); await app.init(); }); afterEach(async () => { await app.close(); }); it('should trigger FileInterceptor logic when uploading a file', async () => { return request(app.getHttpServer()) .post('/your-upload-endpoint') // 替换为你的控制器上传路由 // 传入名为'file'的模拟文件:内容、原始文件名 .attach('file', Buffer.from('test file content'), 'demo.txt') .expect(201); // 根据你的接口返回状态码调整 }); });
2. 关键覆盖点说明
.attach('file', ...)中的第一个参数'file'必须和FileInterceptor('file', ...)中的字段名完全一致,否则拦截器不会触发- 传入的文件需要包含原始文件名(如
demo.txt),这样extname(file.originalname)会执行,覆盖后缀名处理逻辑 - 模拟的文件内容非空,会进入
if (file)分支,覆盖随机文件名生成的代码
3. 可选:避免真实文件写入
如果不想测试时真的在./uploads目录生成文件,可以mockdiskStorage模块:
// 在测试文件顶部mock diskStorage jest.mock('@nestjs/platform-express', () => ({ ...jest.requireActual('@nestjs/platform-express'), diskStorage: jest.fn(() => ({ _handleFile: jest.fn((req, file, cb) => cb(null, { path: 'mock-path', filename: 'mock-filename' })), _removeFile: jest.fn((req, file, cb) => cb(null)), })), }));
内容的提问来源于stack exchange,提问作者AartiVerma
相关产品推荐
相关产品推荐

