如何为NestJS字段删除拦截器编写测试用例?
正确编写NestJS拦截器测试用例的方法
你的测试用例存在几个核心问题:
- 未正确模拟
next.handle()返回的Observable(拦截器依赖rxjs的流处理逻辑) - 直接await拦截器返回值(Observable不能直接通过await获取结果,需订阅或转成Promise)
- 模拟的响应结构与拦截器的处理逻辑不匹配
以下是修正后的完整测试代码:
import { of } from 'rxjs'; import { firstValueFrom } from 'rxjs'; import { Transform } from './your-interceptor-file-path'; // 替换为实际文件路径 describe('Transform Interceptor', () => { let transformInterceptor: Transform; beforeEach(() => { transformInterceptor = new Transform(); }); it('should delete `name` from response if present', async () => { // 构造包含name字段的测试响应 const mockResponse = { value: { name: 'Test Name', age: 25 } }; // 正确模拟CallHandler,返回带测试数据的Observable const next = { handle: jest.fn().mockReturnValue(of(mockResponse)) }; // 模拟ExecutionContext(拦截器未用到context具体逻辑,简化处理) const context = {} as ExecutionContext; // 将Observable转为Promise,方便用await获取结果 const processedResponse = await firstValueFrom( transformInterceptor.intercept(context, next) ); // 验证name字段已被删除,其他字段保留 expect(processedResponse.value.name).toBeUndefined(); expect(processedResponse.value.age).toBe(25); }); // 可选:测试响应无name字段的情况 it('should not modify response when `name` is missing', async () => { const mockResponse = { value: { age: 25, email: 'test@example.com' } }; const next = { handle: jest.fn().mockReturnValue(of(mockResponse)) }; const context = {} as ExecutionContext; const processedResponse = await firstValueFrom( transformInterceptor.intercept(context, next) ); expect(processedResponse.value).toEqual(mockResponse.value); }); });
关键修正说明:
- 用
rxjs的of()创建Observable,匹配NestJS拦截器的流处理机制 - 通过
firstValueFrom将Observable转为Promise,支持用await获取处理结果(也可通过订阅Observable的方式实现) - 构造符合拦截器处理逻辑的mock响应(包含
value属性) - 补充了边界场景测试,确保拦截器在无name字段时不会破坏原有响应
注:如果你的拦截器类实际名为TransformRepoResponse,请将代码中的Transform替换为对应类名,保持代码一致性。
内容的提问来源于stack exchange,提问作者Tony Mathew
相关产品推荐
相关产品推荐

