Some checks are pending
Docker Test / test (push) Waiting to run
This commit adds comprehensive unit tests for the role-based access control middleware and fixes the ES module export issue. The tests verify that users with correct roles can access protected routes, while users with incorrect roles or no authentication are properly denied access.
88 lines
No EOL
2.3 KiB
JavaScript
88 lines
No EOL
2.3 KiB
JavaScript
import request from 'supertest';
|
|
import app from '../app.js';
|
|
import { requireRole } from '../middleware/role.middleware.js';
|
|
|
|
describe('Role-based Access Control', () => {
|
|
// Test that the middleware is properly exported
|
|
test('requireRole should be a function', () => {
|
|
expect(typeof requireRole).toBe('function');
|
|
});
|
|
|
|
// Mock user authentication for testing
|
|
const mockUser = (role) => {
|
|
return {
|
|
role: role,
|
|
id: 'test-user-id'
|
|
};
|
|
};
|
|
|
|
// Test that middleware allows access to users with correct roles
|
|
test('should allow access to users with correct roles', () => {
|
|
const req = {
|
|
user: mockUser('admin')
|
|
};
|
|
const res = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn()
|
|
};
|
|
const next = jest.fn();
|
|
|
|
const middleware = requireRole(['admin']);
|
|
middleware(req, res, next);
|
|
|
|
expect(next).toHaveBeenCalled();
|
|
});
|
|
|
|
// Test that middleware denies access to users with incorrect roles
|
|
test('should deny access to users with incorrect roles', () => {
|
|
const req = {
|
|
user: mockUser('user')
|
|
};
|
|
const res = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn()
|
|
};
|
|
const next = jest.fn();
|
|
|
|
const middleware = requireRole(['admin']);
|
|
middleware(req, res, next);
|
|
|
|
expect(res.status).toHaveBeenCalledWith(403);
|
|
expect(res.json).toHaveBeenCalledWith({ error: 'Insufficient permissions' });
|
|
});
|
|
|
|
// Test that middleware denies access to unauthenticated users
|
|
test('should deny access to unauthenticated users', () => {
|
|
const req = {
|
|
user: null
|
|
};
|
|
const res = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn()
|
|
};
|
|
const next = jest.fn();
|
|
|
|
const middleware = requireRole(['admin']);
|
|
middleware(req, res, next);
|
|
|
|
expect(res.status).toHaveBeenCalledWith(401);
|
|
expect(res.json).toHaveBeenCalledWith({ error: 'Authentication required' });
|
|
});
|
|
|
|
// Test that middleware allows access to users with one of multiple roles
|
|
test('should allow access to users with one of multiple roles', () => {
|
|
const req = {
|
|
user: mockUser('moderator')
|
|
};
|
|
const res = {
|
|
status: jest.fn().mockReturnThis(),
|
|
json: jest.fn()
|
|
};
|
|
const next = jest.fn();
|
|
|
|
const middleware = requireRole(['admin', 'moderator']);
|
|
middleware(req, res, next);
|
|
|
|
expect(next).toHaveBeenCalled();
|
|
});
|
|
}); |