nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.44k stars 7.6k forks source link

How to override APP_GUARD for e2e testing #5821

Closed davids-sparkshare closed 3 years ago

davids-sparkshare commented 3 years ago

Bug Report

Current behavior

When registering a auth guard as global APP_GUARD, it is not possible (or at least not documented how) to override that guard for testing.

Input Code

Full example with e2e test at https://github.com/davids-sparkshare/override-repro

Registering the LocalAuthGuard:

@Module({
  imports: [PassportModule],
  providers: [
    AuthService,
    LocalStrategy,
    {
      provide: APP_GUARD,
      useClass: LocalAuthGuard,
    },
  ],
})
export class AuthModule {}

from https://github.com/davids-sparkshare/override-repro/blob/bac4580e1755948f0f928b21bd70bf5152948154/src/auth/auth.module.ts#L8-L19

Trying to override it with a TestAuthGuard in the e2e tests:

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

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

from https://github.com/davids-sparkshare/override-repro/blob/bac4580e1755948f0f928b21bd70bf5152948154/test/app.e2e-spec.ts#L12-L24

Expected behavior

There is a documented way to replace the APP_GUARD for test mocking.

Environment


Nest version: 7.5.1
jmcdo29 commented 3 years ago

4053