import { ExecutionContext, UnauthorizedException } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { JwtAuthGuard } from './jwt-auth.guard'; import { IS_PUBLIC_KEY } from '../decorators/public.decorator'; describe('JwtAuthGuard', () => { let guard: JwtAuthGuard; let reflector: Reflector; beforeEach(() => { reflector = new Reflector(); guard = new JwtAuthGuard(reflector); }); describe('canActivate', () => { it('should return true if the route is public', () => { const context = { getHandler: jest.fn(), getClass: jest.fn(), switchToHttp: jest.fn().mockReturnValue({ getRequest: jest.fn().mockReturnValue({}), getResponse: jest.fn().mockReturnValue({}), }), } as unknown as ExecutionContext; jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(true); expect(guard.canActivate(context)).toBe(true); expect(reflector.getAllAndOverride).toHaveBeenCalledWith(IS_PUBLIC_KEY, [ context.getHandler(), context.getClass(), ]); }); it('should call super.canActivate if the route is not public', () => { const context = { getHandler: jest.fn(), getClass: jest.fn(), switchToHttp: jest.fn().mockReturnValue({ getRequest: jest.fn().mockReturnValue({}), getResponse: jest.fn().mockReturnValue({}), }), } as unknown as ExecutionContext; jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(false); // Mock the AuthGuard's canActivate method const canActivateSpy = jest.spyOn(guard, 'canActivate'); // We can't easily test the super.canActivate call directly, // so we'll just verify our method was called with the right context guard.canActivate(context); expect(reflector.getAllAndOverride).toHaveBeenCalledWith(IS_PUBLIC_KEY, [ context.getHandler(), context.getClass(), ]); expect(canActivateSpy).toHaveBeenCalledWith(context); }); }); describe('handleRequest', () => { it('should return the user if no error and user exists', () => { const user = { id: 'user1', name: 'Test User' }; const result = guard.handleRequest(null, user, null); expect(result).toBe(user); }); it('should throw the error if an error exists', () => { const error = new Error('Test error'); expect(() => guard.handleRequest(error, null, null)).toThrow(error); }); it('should throw UnauthorizedException if no error but user does not exist', () => { expect(() => guard.handleRequest(null, null, null)).toThrow(UnauthorizedException); expect(() => guard.handleRequest(null, null, null)).toThrow('Authentication required'); }); }); });