如何测试 NestJs 响应拦截器

How to test NestJs response interceptor

我尝试按照 进行操作,但我一直收到错误消息。

变换-response.interceptor.ts:

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponseInterface } from '@walletxp/shared-interfaces';

@Injectable()
export class TransformResponseInterceptor<T>
  implements NestInterceptor<T, ApiResponseInterface<Record<string, unknown>>>
{
  intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponseInterface<Record<string, unknown>>> {
    return next.handle().pipe(map((data) => ({ success: true, data })));
  }
}

为了测试,transform-response.interceptor.spec.ts:

import { TransformResponseInterceptor } from './transform-response.interceptor';
const interceptor = new TransformResponseInterceptor();

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

const callHandler = {
  handle: jest.fn(),
};

describe('ResponseInterceptor', () => {
  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);
    });
  });
});

我的目标是模拟从控制器返回的数据并检查它在通过拦截器后是否等于我想要的格式化数据。

我已经使用对应用程序的调用测试了我的拦截器,更像是端到端测试。

import { Test, TestingModule } from '@nestjs/testing';
import * as request from 'supertest';
import { INestApplication, HttpStatus } from '@nestjs/common';

import { EmulatorHeadersInterceptor } from '@LIBRARY/interceptors/emulator-headers.interceptor';

import { AppModule } from '@APP/app.module';

describe('Header Intercepter', () => {
    let app: INestApplication;

    afterAll(async () => {
        await app.close();
    });

    beforeAll(async () => {
        const moduleFixture: TestingModule = await Test.createTestingModule({
            imports: [AppModule],
        }).compile();

        app = moduleFixture.createNestApplication();
        app.useGlobalInterceptors(new EmulatorHeadersInterceptor());
        await app.init();
    });

    it('./test (PUT) should have the interceptor data', async () => {
        const ResponseData$ = await request(app.getHttpServer())
            .put('/test')
            .send();

        expect(ResponseData$.status).toBe(HttpStatus.OK);
        expect(ResponseData$.headers['myheader']).toBe('interceptor');
    });
});

我的拦截器正在添加一个 header 字段,但是对于您的拦截器,您可以用您的拦截器替换我正在使用的 header 拦截器。从那里,您可以测试响应是否包含您想要的内容。

如果您正在寻找简单的单元测试,那么您需要了解 RxJS 如何进行异步测试。像下面这样的东西可以工作:

describe('ResponseInterceptor', () => {
  let interceptor: ResponseInterceptor;

  beforeEach(() => {
    interceptor = new ResponseInterceptor();
  });

  it('should map the data', (done) => {
    // this sets up a mock execution context (which you don't use so it's blank)
    // and a mock CallHandler that returns a known piece of data 'test data'
    const obs$ = interceptor.intercept({} as any, { handle: () => of('test data') });
    // this tests the observable, and calls done when it is complete
    obs$.subscribe({
      next: (val) => {
        expect(val).toEqual({ success: true, data: 'test data' })
      }),
      complete: () => done()
    })
  });

});

我将展示我项目中的一个简单而清晰的现实世界示例。该示例类似于问题中显示的关于使用拦截器转换对象的示例。我使用此拦截器从作为 response:

发送的 user 对象中排除 hashedPassword 等敏感属性
describe('SerializerInterceptor', () => {
  let interceptor: SerializerInterceptor

  beforeEach(() => {
    interceptor = new SerializerInterceptor(UserDto)
  })

  it('should return user object without the sensitive properties', async () => {

    const context = createMock<ExecutionContext>()
    const handler = createMock<CallHandler>({
      handle: () => of(testUser)
    })

    const userObservable = interceptor.intercept(context, handler)
    const user = await lastValueFrom(userObservable)

    expect(user.id).toEqual(testUser.id)
    expect(user.username).toEqual(testUser.username)

    expect(user).not.toHaveProperty('hashedPassword')
  })
})

为了模拟 ExecutionContextCallHandler,我们使用 @golevelup/ts-jest 包中的 createMock() 函数。

NestJS Interceptor 底层使用 RxJS。因此,当框架调用其 intercept() 方法时,它 returns 我们对象的 Observable 。为了从这个 Observable 中干净地提取我们的值,我们使用 RxJS 中的便利函数 lastValueFrom()

这里的testUser,就是你要测试的对象。您需要创建它并将其提供给如上所示的模拟处理程序。