如何测试 Nestjs 拦截器? [英] How to test Nestjs interceptor?

查看:28
本文介绍了如何测试 Nestjs 拦截器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't find any explanation on how to test interceptors in NestJS

这个简单的示例拦截了一个 POST 查询,以将一个属性添加到正文中提供的示例模型中.

This simple example intercepts a POST query to add an attribute to an Example Model provided in the body.

@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();
  }
}

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

I would like to test what's happening in the intercept function.

到目前为止:

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?否则我应该如何进行?

My question: Should I mock only arg1: ExecutionContext and arg2: CallHandler? If so, how to mock arg1 and arg2? Else How should I proceed?

推荐答案

你说得对,你应该模拟 arg1arg2,然后将它们传递给 拦截方法,解决方法如下:

You are right, you should mock the arg1 and arg2,then pass them to intercept method, here is the solution:

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

这篇关于如何测试 Nestjs 拦截器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆