- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
72 lines
2.4 KiB
TypeScript
72 lines
2.4 KiB
TypeScript
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>(RolesGuard);
|
|
reflector = module.get<Reflector>(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);
|
|
});
|
|
});
|