相关疑难解决方法(0)

如何测试 Nestjs 拦截器?

我找不到关于如何在 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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

迄今为止:

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: …
Run Code Online (Sandbox Code Playgroud)

unit-testing interceptor typescript jestjs nestjs

4
推荐指数
1
解决办法
4327
查看次数

标签 统计

interceptor ×1

jestjs ×1

nestjs ×1

typescript ×1

unit-testing ×1