import { Test, TestingModule } from "@nestjs/testing"; import { RolesGuard } from "./roles.guard"; import { Reflector } from "@nestjs/core"; import { ExecutionContext, ForbiddenException } from "@nestjs/common"; import { ROLES_KEY } from "../decorators/roles.decorator"; describe("RolesGuard", () => { let guard: RolesGuard; let reflector: Reflector; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ RolesGuard, { provide: Reflector, useValue: { getAllAndOverride: jest.fn(), }, }, ], }).compile(); guard = module.get(RolesGuard); reflector = module.get(Reflector); }); const createMockContext = (user?: any): ExecutionContext => { return { getHandler: jest.fn(), getClass: jest.fn(), switchToHttp: () => ({ getRequest: () => ({ user }), }), } as any; }; it("should be defined", () => { expect(guard).toBeDefined(); }); it("should allow access if no roles are required", () => { jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(undefined); const context = createMockContext({ role: "User_PetOwner" }); expect(guard.canActivate(context)).toBe(true); }); it("should throw ForbiddenException if user is missing", () => { jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(["Admin"]); const context = createMockContext(undefined); expect(() => guard.canActivate(context)).toThrow(ForbiddenException); }); it("should throw ForbiddenException if user has non-matching role", () => { jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(["Admin"]); const context = createMockContext({ role: "User_PetOwner" }); expect(() => guard.canActivate(context)).toThrow(ForbiddenException); }); it("should allow access if user has matching role", () => { jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(["Admin"]); const context = createMockContext({ role: "Admin" }); expect(guard.canActivate(context)).toBe(true); }); it("should allow access if user has case-insensitive matching admin role", () => { jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(["Admin"]); const context = createMockContext({ role: "SUPER_ADMIN" }); expect(guard.canActivate(context)).toBe(true); }); });