helpyourneighbour/backend/tests/requireRole.test.js
J.A.R.V.I.S. 6ba032b990
Some checks are pending
Docker Test / test (push) Waiting to run
feat: add unit tests for requireRole middleware
This commit adds unit tests for the requireRole middleware to ensure proper role-based access control implementation. The tests cover successful access, insufficient permissions, and unauthorized access scenarios.
2026-03-20 04:07:26 +00:00

56 lines
No EOL
1.7 KiB
JavaScript

const { requireRole, hasRole } = require('../src/middleware/requireRole');
describe('requireRole middleware', () => {
it('should allow access for users with correct role', () => {
const req = { user: { role: '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();
expect(res.status).not.toHaveBeenCalled();
});
it('should deny access for users with incorrect role', () => {
const req = { user: { role: 'user' } };
const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn()
};
const next = jest.fn();
const middleware = requireRole(['admin']);
middleware(req, res, next);
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenCalledWith({ error: 'Insufficient permissions' });
});
it('should deny access for 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(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ error: 'Authorization required' });
});
it('should correctly check role with hasRole helper', () => {
expect(hasRole('admin', ['admin'])).toBe(true);
expect(hasRole('user', ['admin'])).toBe(false);
expect(hasRole('moderator', ['admin', 'moderator'])).toBe(true);
});
});