如何在Nestjs测试中重写身份验证中间件?

问题描述 投票:0回答:1

我在 NestJS 应用程序中进行了 e2e 测试,我想测试受某些身份验证中间件保护的路径。

import { Test, TestingModule } from '@nestjs/testing';
import { AppModule } from '../src/app.module';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';

fdescribe('App health (e2e)', () => {
  let app: INestApplication;

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

    app = moduleFixture.createNestApplication();
    await app.init();
  });


  // override authentication middleware should come here
  it('should fetch a doc which is not public', () => {
    return request(app.getHttpServer())
      .get('/some/protected/path')
      .expect(200)
  });


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

身份验证中间件是通过应用程序中的模块之一激活的,如下所示:

export class PagesModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer
      .apply(UserMiddleware)
      .forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}

我有办法覆盖和替换这个身份验证中间件吗?我可以只更换一次测试吗?

jestjs nestjs e2e-testing nestjs-testing
1个回答
0
投票

显然这仍然是一个悬而未决的问题:https://github.com/nestjs/nest/issues/4073

但是有一个解决方法: 要重新配置测试模块:

@Module({
  imports: [AppModule],
})
export class TestAuthOverride implements NestModule {
  constructor(){
  }
  configure(consumer: MiddlewareConsumer) {
    consumer.apply((req, res, next) => {
      //override here
      next();})
    .forRoutes({ path: '*', method: RequestMethod.ALL });
    
  }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.