Added detailed unit tests for the requireRole middleware to ensure proper role-based access control implementation.
58 lines
No EOL
1.9 KiB
JavaScript
58 lines
No EOL
1.9 KiB
JavaScript
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' });
|
|
});
|
|
}); |