diff --git a/backend/test/roles.test.js b/backend/test/roles.test.js new file mode 100644 index 0000000..3a0fa87 --- /dev/null +++ b/backend/test/roles.test.js @@ -0,0 +1,58 @@ +const request = require('supertest'); +const app = require('../src/server'); +const { requireRole } = require('../middleware/role.middleware'); + +describe('Role Middleware', () => { + describe('requireRole middleware', () => { + it('should allow access for users with correct role', () => { + // This test would need to mock JWT verification and user role + // For now, we just verify the middleware function exists + expect(typeof requireRole).toBe('function'); + }); + + it('should deny access for users without required role', () => { + // This test would also need mocking of JWT and role checking + // For now, we just verify the middleware function exists + expect(typeof requireRole).toBe('function'); + }); + }); +}); + +// New comprehensive tests for role middleware +describe('Role Middleware - Comprehensive Tests', () => { + const mockReq = { + user: { role: 'user' } + }; + + const mockRes = { + status: jest.fn().mockReturnThis(), + json: jest.fn() + }; + + const mockNext = jest.fn(); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should call next() when user has required role', () => { + const middleware = requireRole(['user']); + middleware(mockReq, mockRes, mockNext); + expect(mockNext).toHaveBeenCalled(); + }); + + it('should return 403 when user does not have required role', () => { + const middleware = requireRole(['admin']); + middleware(mockReq, mockRes, mockNext); + expect(mockRes.status).toHaveBeenCalledWith(403); + expect(mockRes.json).toHaveBeenCalledWith({ error: 'Forbidden' }); + }); + + it('should return 401 when no user role is found', () => { + const middleware = requireRole(['user']); + const reqWithoutRole = { user: null }; + middleware(reqWithoutRole, mockRes, mockNext); + expect(mockRes.status).toHaveBeenCalledWith(401); + expect(mockRes.json).toHaveBeenCalledWith({ error: 'Unauthorized' }); + }); +}); \ No newline at end of file