Jest.js OverrideProvider不适用于NestJS测试模块中的PrivilegesGuard

eanckbw9  于 2023-05-21  发布在  Jest
关注(0)|答案(1)|浏览(230)

我试图在NestJS测试模块中覆盖PrivilegesGuard提供程序,但它似乎没有按预期工作。我已经遵循了overrideProvider方法的正确语法,但是重写没有生效。
下面是相关的代码片段:

beforeAll(async () => {
  const moduleRef = await Test.createTestingModule({
    imports: [AppModule],
    providers: [ExceptionsService, JwtService, EnvironmentConfigService],
  })
    .overrideProvider(PrivilegesGuard)
    .useClass(MockGuard)
    .compile();

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

我已经验证了PrivilegesGuard提供程序已正确导入,并且没有冲突的导入或声明。我还确保提供给useClass的mockGuard类正确地实现了所需的方法。
但是,不会重写PrivilegesGuard提供程序,仍在使用原始实现。我已经检查了文档和示例,但我找不到解决方案。
有人能帮助我理解为什么在这种情况下,overrideProvider方法对PrivilegesGuard提供程序不起作用吗?任何建议或见解将不胜感激。

@Injectable()
class PrivilegesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const contextPrivileges: PrivilegesMetadata = this.reflector.getAllAndOverride<PrivilegesMetadata>(PRIVILEGES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!contextPrivileges) {
      return true;
    }

    const user: ActiveUserData = getUserFromContext(context);

  
       if (!user.role || !user.role.privileges || user.role.privileges.length === 0) {
      return false;
    }
  

    const requiredEntities = user.role.privileges.filter(
      (priv) => priv.entity === contextPrivileges.intentionEntityKey,
    );

    if (requiredEntities.length === 0) {
      return false;
    }

    const hasPrivilege = contextPrivileges.privileges.every((priv) =>
      requiredEntities.some((req) => req.privilege === priv),
    );

    return hasPrivilege;
  }
}

export default PrivilegesGuard;

模拟守卫

class MockGuard {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    return true;
  }
}

错误:Error image
my test result
我试图使用此代码作为文档解决方案,但不幸的是,我遇到了同样的问题。

beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
      providers: [
        ExceptionsService,
        JwtService,
        EnvironmentConfigService,
        {
          provide: APP_GUARD,
          useExisting: PrivilegesGuard,
        },
        {
          provide: APP_GUARD,
          useExisting: RolesGuard,
        },
        RolesGuard,
        PrivilegesGuard,
      ],
    })
      .overrideProvider(PrivilegesGuard)
      .useClass(MockGuard)
      .overrideProvider(RolesGuard)
      .useClass(MockGuard)
      .overrideProvider(AccessTokenGuard)
      .useClass(MockGuard)
      .overrideProvider(PostServiceImplementation)
      .useValue(mockPostService)
      .compile();

    app = moduleRef.createNestApplication();
    await app.init();
  });
3pvhb19x

3pvhb19x1#

需要在您的模块中使用'useExisting',而不是在测试中:

@Module({
  providers: [
    AccessTokenGuard,
    EnvironmentConfigService,
    ExceptionsService,
    JwtService,
    {
      provide: HashingService,
      useClass: BcryptService,
    },
    {
      provide: APP_GUARD,
      useClass: AuthenticationGuard,
    },
    {
      provide: APP_GUARD,
      useExisting: RolesGuard, // here
    },
    {
      provide: APP_GUARD,
      useExisting: PrivilegesGuard,//here
    },
    RolesGuard,
    PrivilegesGuard,
  ],
  exports: [HashingService],
})
class IamModule {}

export default IamModule;

现在它可以在测试中被覆盖。
联系我们

相关问题