Add unit tests for role-based access control
Some checks are pending
Docker Test / test (push) Waiting to run

This commit is contained in:
BibaBot 2026-03-17 11:07:20 +00:00
parent 963d8c3aa5
commit f0a9084d59
2 changed files with 68 additions and 24 deletions

View file

@ -1,18 +1,12 @@
export default { export default {
testEnvironment: 'node', testEnvironment: 'node',
transform: {
'^.+\\.js$': 'babel-jest'
},
testMatch: [ testMatch: [
'**/tests/**/*.test.js', '**/tests/**/*.test.js'
'**/__tests__/**/*.js'
], ],
moduleNameMapper: { collectCoverageFrom: [
'^src/(.*)$': '<rootDir>/src/$1', 'src/**/*.js',
'^backend/(.*)$': '<rootDir>/$1' '!src/__tests__/**/*.js'
}, ],
transformIgnorePatterns: [ coverageDirectory: 'coverage',
'/node_modules/', verbose: true
'/backend/src/__tests__/'
]
}; };

View file

@ -1,16 +1,66 @@
// Simple test for role middleware // Mock the middleware directly for testing
const fs = require('fs'); const { requireRole } = require('../middleware/role.middleware');
const path = require('path');
describe('Role Middleware Tests', () => { describe('Role-based Access Control', () => {
it('should have a role middleware file', () => { // Test that the middleware exists and is a function
const middlewarePath = path.join(__dirname, '../middleware/role.middleware.js'); test('requireRole should be a function', () => {
expect(fs.existsSync(middlewarePath)).toBe(true); expect(typeof requireRole).toBe('function');
}); });
it('should contain the requireRole function', () => { // Test that middleware allows access for users with correct role
const middlewarePath = path.join(__dirname, '../middleware/role.middleware.js'); test('should allow access for user with correct role', () => {
const content = fs.readFileSync(middlewarePath, 'utf8'); const mockReq = {
expect(content).toContain('requireRole'); 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();
}); });
}); });