feat: add unit tests for requireRole middleware
Some checks are pending
Docker Test / test (push) Waiting to run
Some checks are pending
Docker Test / test (push) Waiting to run
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.
This commit is contained in:
parent
724d49ed2c
commit
6ba032b990
3 changed files with 118 additions and 3 deletions
56
backend/tests/requireRole.test.js
Normal file
56
backend/tests/requireRole.test.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue