38 lines
1.1 KiB
TypeScript
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);
|
|
});
|
|
});
|