55 lines
No EOL
1.7 KiB
JavaScript
55 lines
No EOL
1.7 KiB
JavaScript
const { requireRole } = require('../middleware/role.middleware');
|
|
|
|
describe('Role-based Access Control', () => {
|
|
// Test that the middleware exists and is a function
|
|
test('requireRole should be a function', () => {
|
|
expect(typeof requireRole).toBe('function');
|
|
});
|
|
|
|
// Test that middleware allows access for users with correct role
|
|
test('should allow access for user with correct role', () => {
|
|
// This would need to be implemented with actual JWT mocking
|
|
// For now, just testing the middleware structure
|
|
const mockReq = { user: { role: 'admin' } };
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn()
|
|
};
|
|
const mockNext = jest.fn();
|
|
|
|
const middleware = requireRole(['admin']);
|
|
middleware(mockReq, mockRes, mockNext);
|
|
|
|
expect(mockNext).toHaveBeenCalled();
|
|
});
|
|
|
|
// Test that middleware denies access for users with incorrect role
|
|
test('should deny access for user with incorrect role', () => {
|
|
const mockReq = { user: { role: 'user' } };
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn()
|
|
};
|
|
const mockNext = jest.fn();
|
|
|
|
const middleware = requireRole(['admin']);
|
|
middleware(mockReq, mockRes, mockNext);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
});
|
|
|
|
// Test that middleware denies access for unauthenticated users
|
|
test('should deny access for unauthenticated user', () => {
|
|
const mockReq = { };
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn()
|
|
};
|
|
const mockNext = jest.fn();
|
|
|
|
const middleware = requireRole(['admin']);
|
|
middleware(mockReq, mockRes, mockNext);
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(401);
|
|
});
|
|
}); |