Some checks are pending
Docker Test / test (push) Waiting to run
This commit adds comprehensive unit tests for the requireRole middleware to ensure proper role-based access control.
83 lines
No EOL
2.4 KiB
JavaScript
83 lines
No EOL
2.4 KiB
JavaScript
const request = require('supertest');
|
|
const app = require('../app');
|
|
const { requireRole } = require('../middleware/role.middleware');
|
|
|
|
describe('Role Middleware', () => {
|
|
// Mock a user with a specific role for testing
|
|
const mockUserWithRole = (role) => {
|
|
return {
|
|
role: role,
|
|
id: 'test-user-id'
|
|
};
|
|
};
|
|
|
|
// Test that the middleware allows access to users with correct roles
|
|
test('should allow access to users with correct roles', () => {
|
|
const mockReq = {
|
|
user: mockUserWithRole('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 the middleware denies access to users with incorrect roles
|
|
test('should deny access to users with incorrect roles', () => {
|
|
const mockReq = {
|
|
user: mockUserWithRole('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);
|
|
expect(mockRes.json).toHaveBeenCalledWith({ error: 'Forbidden' });
|
|
});
|
|
|
|
// Test that the middleware denies access to users without roles
|
|
test('should deny access to users without roles', () => {
|
|
const mockReq = {
|
|
user: null
|
|
};
|
|
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);
|
|
expect(mockRes.json).toHaveBeenCalledWith({ error: 'Unauthorized' });
|
|
});
|
|
|
|
// Test that the middleware allows access to users with one of multiple required roles
|
|
test('should allow access to users with one of multiple required roles', () => {
|
|
const mockReq = {
|
|
user: mockUserWithRole('moderator')
|
|
};
|
|
const mockRes = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn()
|
|
};
|
|
const mockNext = jest.fn();
|
|
|
|
const middleware = requireRole(['admin', 'moderator']);
|
|
middleware(mockReq, mockRes, mockNext);
|
|
|
|
expect(mockNext).toHaveBeenCalled();
|
|
});
|
|
}); |