如何测试 Nestjs 拦截器?

     2023-03-10     24

关键词:

【中文标题】如何测试 Nestjs 拦截器?【英文标题】:How to test Nestjs interceptor? 【发布时间】:2020-01-03 21:47:00 【问题描述】:

我找不到任何关于如何在 NestJS 中测试拦截器的解释

这个简单的例子截取了一个 POST 查询以向正文中提供的示例模型添加一个属性。

@Injectable()
export class SubscriberInterceptor implements NestInterceptor 
  async intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Promise<Observable<ExampleModel>> 
    let body: ExampleModel = context.switchToHttp().getRequest().body;
    body = 
      ...body,
      addedAttribute: 'example',
    ;
    context.switchToHttp().getRequest().body = body;
    return next.handle();
  

我想测试拦截函数中发生了什么。

到目前为止:

const interceptor = new SubscriberInterceptor();

describe('SubscriberInterceptor', () => 
  it('should be defined', () => 
    expect(interceptor).toBeDefined();
  );

  describe('#intercept', () => 
    it('should add the addedAttribute to the body', async () => 
      expect(await interceptor.intercept(arg1, arg2)).toBe( ...bodyMock, addedAttribute: 'example' );
    );
  );
);

我的问题:我应该只模拟 arg1: ExecutionContextarg2: CallHandler 吗?如果是这样,如何模拟arg1arg2?否则我应该如何进行?

【问题讨论】:

【参考方案1】:

你是对的,你应该模拟arg1arg2,然后将它们传递给intercept方法,这里是解决方案:

SubscriberInterceptor.ts:

interface ExecutionContext 
  switchToHttp(): any;

interface CallHandler 
  handle(): any;

interface Observable<T> 
interface ExampleModel 

interface NestInterceptor 
  intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<ExampleModel>>;


export class SubscriberInterceptor implements NestInterceptor 
  public async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<ExampleModel>> 
    let body: ExampleModel = context.switchToHttp().getRequest().body;
    body = 
      ...body,
      addedAttribute: 'example'
    ;
    context.switchToHttp().getRequest().body = body;
    return next.handle();
  


单元测试,executionContext的模拟链式方法

import  SubscriberInterceptor  from './';

const interceptor = new SubscriberInterceptor();

const executionContext = 
  switchToHttp: jest.fn().mockReturnThis(),
  getRequest: jest.fn().mockReturnThis()
;

const callHandler = 
  handle: jest.fn()
;

describe('SubscriberInterceptor', () => 
  it('should be defined', () => 
    expect(interceptor).toBeDefined();
  );
  describe('#intercept', () => 
    it('t1', async () => 
      (executionContext.switchToHttp().getRequest as jest.Mock<any, any>).mockReturnValueOnce(
        body:  data: 'mocked data' 
      );
      callHandler.handle.mockResolvedValueOnce('next handle');
      const actualValue = await interceptor.intercept(executionContext, callHandler);
      expect(actualValue).toBe('next handle');
      expect(executionContext.switchToHttp().getRequest().body).toEqual(
        data: 'mocked data',
        addedAttribute: 'example'
      );
      expect(callHandler.handle).toBeCalledTimes(1);
    );
  );
);

单元测试结果:

 PASS  src/mock-function/57730120/index.spec.ts
  SubscriberInterceptor
    ✓ should be defined (10ms)
    #intercept
      ✓ t1 (11ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.235s, estimated 3s

【讨论】:

当 getRequest 不是 ExecutionContext 的方法时,它是如何工作的?它是从 switchtoHttp() 返回的对象的方法。

如何在nestjs拦截器中检测控制器?

】如何在nestjs拦截器中检测控制器?【英文标题】:Howtoinstrumentacontrollerinnestjsinterceptor?【发布时间】:2021-02-1105:02:41【问题描述】:我想为APM目的检测nestjs控制器的每个方法。为了检测控制器调用,我编写了以下拦截器。但是... 查看详情

如何在 NestJS 拦截器中获取处理程序路由(对于 Express 和 Fastify)

】如何在NestJS拦截器中获取处理程序路由(对于Express和Fastify)【英文标题】:HowtogethandlerrouteinNestJSInterceptor(ForbothExpressandFastify)【发布时间】:2020-06-1920:26:52【问题描述】:我在尝试在我正在编写的拦截器中获取NestJS处理程序... 查看详情

如何在发送 Nestjs 之前格式化响应?

...题描述】:我按照文档进行操作,并能够为响应映射添加拦截器。我想要一个一致的json格式的响应输出。如何使用拦截器或其他比这种方法更好的方法来实现这一点。"statusCode":201,"message":"CustomDynamicMessage 查看详情

如何在 neo4j-graphql-js 端点中使用带有 nestjs 框架的拦截器?

】如何在neo4j-graphql-js端点中使用带有nestjs框架的拦截器?【英文标题】:HowcanIuseinterceptorinneo4j-graphql-jsendpointwithnestjsframework?【发布时间】:2020-02-1107:15:40【问题描述】:我正在使用neo4j-graphql-js库将graphql查询转换为密码,我需... 查看详情

如何在 NestJS 服务中测试猫鼬?

】如何在NestJS服务中测试猫鼬?【英文标题】:HowtotestmongooseinNestJSService?【发布时间】:2019-12-2200:12:58【问题描述】:我想从我的服务中测试getFund()方法。我使用默认使用jest的NestJS。我不知道如何用玩笑来测试这条线:returnawait... 查看详情

如何在 NestJS 中记录所有 Axios 外部 http 请求

...方法。到目前为止,我所做的是基于answer来编写一个Http拦截器exportclassHttpLoggerInterceptorimp 查看详情

NestJS:拦截地图和catchError

...布时间】:2019-11-1714:13:38【问题描述】:我需要一个NestJS拦截器来归档请求,无论是在异常情况还是快乐路径情况下。创建如下:publicintercept(context:ExecutionContext,next:CallHandler):Observable<any& 查看详情

如何拦截特定请求

】如何拦截特定请求【英文标题】:Howtointerceptspecificrequest【发布时间】:2020-09-2017:45:00【问题描述】:我正在使用NestJS和Angular2,两者都有类似(接近)的方法来使用Interceptors。我想找到最佳实践来确定一些特定的请求来做一... 查看详情

单元测试时如何在nestjs中为服务提供注入常量

】单元测试时如何在nestjs中为服务提供注入常量【英文标题】:HowtoprovideInjectedconstanttoserviceinnestjswhenunittesting【发布时间】:2019-03-0101:30:56【问题描述】:我尝试为我的小型应用程序创建单元测试。我想测试一个使用注入配置和... 查看详情

如何对 NestJS 中的控制器应用警卫进行单元测试?

】如何对NestJS中的控制器应用警卫进行单元测试?【英文标题】:HowcanIunittestthataguardisappliedonacontrollerinNestJS?【发布时间】:2020-05-0303:53:51【问题描述】:我在NestJS中配置了一个控制器,我想检查是否设置了适当的保护-有没有人... 查看详情

NestJS + Mongoose:如何测试 document(data).save()?

】NestJS+Mongoose:如何测试document(data).save()?【英文标题】:NestJS+Mongoose:Howtotestfordocument(data).save()?【发布时间】:2021-01-3123:04:18【问题描述】:由于我使用了一些抽象,这里的代码只接收一个用户,将其更改为Mongo格式(也就是... 查看详情

如何对完整覆盖的 NestJs http 请求进行单元测试?

】如何对完整覆盖的NestJshttp请求进行单元测试?【英文标题】:HowtounittestNestJshttprequestwithfullcoverage?【发布时间】:2020-08-1310:45:20【问题描述】:我无法测试我的NestJs服务。我写了一个方法,它执行GEThttp请求:getEntries():Observable... 查看详情

nestjs文件上传

参考技术A文件上传需要使用拦截器UseInterceptors在\'@nestjs/common\'包内拦截器功能参考:https://docs.nestjs.cn/7/interceptors单文件上传所需依赖有FileInterceptor,UploadedFileFileInterceptor是拦截器负责处理请求接口后的文件再使用UploadedFile进行接... 查看详情

单元测试 Nestjs Mongoose 服务

...时间】:2019-11-2205:38:48【问题描述】:我一直试图弄清楚如何对服务NestJS进行单元测试。所以我写了一个规范文件来测试这些使用mongoose的NestJS服务。spec文件如下:importTest,TestingModulefrom\'@nestjs/testing\';importEv 查看详情

NestJS如何在单元测试中创建新的猫鼬模型?

】NestJS如何在单元测试中创建新的猫鼬模型?【英文标题】:NestJShowtocreatenewmongooseModelinunittest?【发布时间】:2019-10-1010:05:30【问题描述】:我尝试对我的NestJsController类进行单元测试。我已经使用ts-mockito模拟了我的服务,但现... 查看详情

在 NestJS 中测试解析器

...内部也可能没有多少逻辑,因此最好也对它们进行测试。如何测试resolver文件?importObjectIdfrom\'mongod 查看详情

如何通过传入具有自定义值的 ConfigService 来测试 nestjs 服务?

】如何通过传入具有自定义值的ConfigService来测试nestjs服务?【英文标题】:HowtotestanestjsservicebypassinginaConfigServicewithcustomvalues?【发布时间】:2021-04-1415:10:06【问题描述】:我创建了一个服务,它的模块如下所示:launchdarkly.module.t... 查看详情

如何使用 nestjs-graphql-fastify 服务器上传文件以及如何测试此类功能?

】如何使用nestjs-graphql-fastify服务器上传文件以及如何测试此类功能?【英文标题】:Howtouploadfileusingnestjs-graphql-fastifyserverandhowtotestsuchfeature?【发布时间】:2022-01-1706:10:00【问题描述】:我很难将.csv文件上传到nestjs-graphql-fastify服... 查看详情