helpyourneighbour/backend/tests/roles.test.js
BibaBot f0a9084d59
Some checks are pending
Docker Test / test (push) Waiting to run
Add unit tests for role-based access control
2026-03-17 11:07:20 +00:00

66 lines
No EOL
1.8 KiB
JavaScript

// Mock the middleware directly for testing
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', () => {
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);
expect(mockRes.json).toHaveBeenCalled();
});
// 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);
expect(mockRes.json).toHaveBeenCalled();
});
});