I am trying to override the PrivilegesGuard provider in a NestJS testing module, but it doesn't seem to be working as expected. I have followed the correct syntax for the overrideProvider method, but the override does not take effect.
Here is the relevant code snippet:
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
providers: [ExceptionsService, JwtService, EnvironmentConfigService],
})
.overrideProvider(PrivilegesGuard)
.useClass(MockGuard)
.compile();
app = moduleRef.createNestApplication();
await app.init();
});
I have verified that the PrivilegesGuard provider is correctly imported and that there are no conflicting imports or declarations. I have also ensured that the mockGuard class provided to useClass properly implements the required methods.
However, the PrivilegesGuard provider is not being overridden, and the original implementation is still being used. I have checked the documentation and examples, but I couldn't find a solution.
Can anyone please help me understand why the overrideProvider method is not working for the PrivilegesGuard provider in this case? Any suggestions or insights would be greatly appreciated.
@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;
Mock Guard
class MockGuard {
async canActivate(context: ExecutionContext): Promise<boolean> {
return true;
}
}
Error: Error image
I attempted to use this code as a documentation workaround, but unfortunately, I encountered the same issue.
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();
});