如何在 NestJS 上测试具有多个守卫的控制器

Vin*_*iel 1 nestjs

我正在测试我的控制器,但我在模拟该控制器的守卫时遇到问题。我的应用程序是使用 NestJs 版本 6.13.1 开发的

我可以覆盖一个守卫来嘲笑它,如下所示:

const fakeGuard: CanActivate = { canActivate: () => true };

beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
        imports: [
            CoreModule,
            AuthModule,
            PermissionsModule,
            UsersModule
        ],
        controllers: [UsersController],
    })
    .overrideGuard(AuthGuard('jwt')).useValue(fakeGuard) // When I have one guard in my controller it works right
    .compile();

    controller = module.get<UsersController>(UsersController);
    app = module.createNestApplication();
    app.init();
});
Run Code Online (Sandbox Code Playgroud)

但在我的场景中,我在控制器中定义了 2 个守卫

@UseGuards(AuthGuard('jwt'), PermissionGuard)
export class UsersController {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我没有找到一种方法来嘲笑多个警卫。当我调用 overrideGuard 时,我尝试通过 2 个守卫,但是当我运行测试时,没有任何异常。但我知道,问题是因为我无法嘲笑那两个警卫。如果您遇到同样的问题,请与我分享您的解决方案,谢谢。

Jay*_*iel 5

您需要指定要使用其自己的覆盖的每个守卫overrideGuard。你可以有一个beforeEach看起来像这样的:

beforeEach(async () => {
  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
  })
    .overrideGuard(Guard1)
    .useValue({ canActivate: () => true })
    .overrideGuard(Guard2)
    .useValue({ canActivate: () => true })
    .compile();

  app = moduleFixture.createNestApplication();
  await app.init();
});
Run Code Online (Sandbox Code Playgroud)

现在两个守卫都会返回 true 并且测试路线可以成功命中