Files
gridpilot.gg/apps/api/src/domain/auth/RequireRoles.test.ts
Marc Mintel 6c07abe5e7
Some checks failed
Contract Testing / contract-snapshot (pull_request) Has been cancelled
Contract Testing / contract-tests (pull_request) Has been cancelled
view data fixes
2026-01-25 00:12:30 +01:00

70 lines
2.2 KiB
TypeScript

import { SetMetadata } from '@nestjs/common';
import { RequireRoles, REQUIRE_ROLES_METADATA_KEY } from './RequireRoles';
// Mock SetMetadata
vi.mock('@nestjs/common', () => ({
SetMetadata: vi.fn(() => (target: unknown, propertyKey: string, descriptor: PropertyDescriptor) => descriptor),
}));
describe('RequireRoles', () => {
it('should return a method decorator', () => {
const decorator = RequireRoles('admin');
expect(typeof decorator).toBe('function');
});
it('should call SetMetadata with correct key and value for single role', () => {
RequireRoles('admin');
expect(SetMetadata).toHaveBeenCalledWith(REQUIRE_ROLES_METADATA_KEY, {
anyOf: ['admin'],
});
});
it('should call SetMetadata with correct key and value for multiple roles', () => {
RequireRoles('admin', 'owner', 'moderator');
expect(SetMetadata).toHaveBeenCalledWith(REQUIRE_ROLES_METADATA_KEY, {
anyOf: ['admin', 'owner', 'moderator'],
});
});
it('should return a decorator that can be used as both method and class decorator', () => {
const decorator = RequireRoles('admin');
// Test as method decorator
const mockTarget = {};
const mockPropertyKey = 'testMethod';
const mockDescriptor = { value: () => {} };
const result = decorator(mockTarget, mockPropertyKey, mockDescriptor);
// The decorator should return the descriptor
expect(result).toBe(mockDescriptor);
});
it('should have correct metadata key', () => {
expect(REQUIRE_ROLES_METADATA_KEY).toBe('gridpilot:requireRoles');
});
it('should handle empty roles array', () => {
const decorator = RequireRoles();
// Test as method decorator
const mockTarget = {};
const mockPropertyKey = 'testMethod';
const mockDescriptor = { value: () => {} };
const result = decorator(mockTarget, mockPropertyKey, mockDescriptor);
expect(result).toBe(mockDescriptor);
});
it('should handle roles with special characters', () => {
RequireRoles('admin-user', 'owner@company');
expect(SetMetadata).toHaveBeenCalledWith(REQUIRE_ROLES_METADATA_KEY, {
anyOf: ['admin-user', 'owner@company'],
});
});
});