sinka/api/src/auth/guards/roles.guard.spec.ts
armando 8e4203e4c9 sinka
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 03:56:18 -03:00

38 lines
1.1 KiB
TypeScript

import { ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RolesGuard } from './roles.guard';
function contextWith(user: unknown): ExecutionContext {
return {
getHandler: () => ({}),
getClass: () => ({}),
switchToHttp: () => ({
getRequest: () => ({ user }),
}),
} as ExecutionContext;
}
describe('RolesGuard', () => {
const reflector = { getAllAndOverride: jest.fn() };
const guard = new RolesGuard(reflector as unknown as Reflector);
beforeEach(() => {
reflector.getAllAndOverride.mockReset();
});
it('allows when the route has no role list', () => {
reflector.getAllAndOverride.mockReturnValue(undefined);
expect(guard.canActivate(contextWith(undefined))).toBe(true);
});
it('allows a matching role', () => {
reflector.getAllAndOverride.mockReturnValue(['ADMIN', 'MANAGER']);
expect(guard.canActivate(contextWith({ role: 'MANAGER' }))).toBe(true);
});
it('blocks an operator on an admin route', () => {
reflector.getAllAndOverride.mockReturnValue(['ADMIN']);
expect(guard.canActivate(contextWith({ role: 'OPERATOR' }))).toBe(false);
});
});