Jest.js 如何在Nestjs测试中覆盖认证中间件?

t5fffqht  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(78)

我在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 });
  }
}


是否有方法覆盖并替换此身份验证中间件?是否可以仅在单个测试中替换它?

ryevplcw

ryevplcw1#

显然,这仍然是一个开放的问题: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 });
    
  }
}

字符串

相关问题