helpyourneighbour/backend/tests/roles.test.js

83 lines
2.4 KiB
JavaScript
Raw Normal View History

const request = require('supertest');
2026-03-17 07:07:36 +00:00
const app = require('../app');
const { requireRole } = require('../middleware/role.middleware');
2026-03-17 07:07:36 +00:00
describe('Role Middleware', () => {
// Mock a user with a specific role for testing
const mockUserWithRole = (role) => {
return {
role: role,
id: 'test-user-id'
};
};
// Test that the middleware allows access to users with correct roles
test('should allow access to users with correct roles', () => {
const mockReq = {
2026-03-17 07:07:36 +00:00
user: mockUserWithRole('admin')
};
const mockRes = {
2026-03-17 07:07:36 +00:00
status: jest.fn().mockReturnThis(),
json: jest.fn()
};
const mockNext = jest.fn();
2026-03-17 07:07:36 +00:00
const middleware = requireRole(['admin']);
middleware(mockReq, mockRes, mockNext);
2026-03-17 07:07:36 +00:00
expect(mockNext).toHaveBeenCalled();
2026-03-17 07:07:36 +00:00
});
// Test that the middleware denies access to users with incorrect roles
test('should deny access to users with incorrect roles', () => {
const mockReq = {
2026-03-17 07:07:36 +00:00
user: mockUserWithRole('user')
};
const mockRes = {
2026-03-17 07:07:36 +00:00
status: jest.fn().mockReturnThis(),
json: jest.fn()
};
const mockNext = jest.fn();
2026-03-17 07:07:36 +00:00
const middleware = requireRole(['admin']);
middleware(mockReq, mockRes, mockNext);
2026-03-17 07:07:36 +00:00
expect(mockRes.status).toHaveBeenCalledWith(403);
expect(mockRes.json).toHaveBeenCalledWith({ error: 'Forbidden' });
});
2026-03-17 07:07:36 +00:00
// Test that the middleware denies access to users without roles
test('should deny access to users without roles', () => {
const mockReq = {
2026-03-17 07:07:36 +00:00
user: null
};
const mockRes = {
2026-03-17 07:07:36 +00:00
status: jest.fn().mockReturnThis(),
json: jest.fn()
};
const mockNext = jest.fn();
2026-03-17 07:07:36 +00:00
const middleware = requireRole(['admin']);
middleware(mockReq, mockRes, mockNext);
2026-03-17 07:07:36 +00:00
expect(mockRes.status).toHaveBeenCalledWith(401);
expect(mockRes.json).toHaveBeenCalledWith({ error: 'Unauthorized' });
});
2026-03-17 07:07:36 +00:00
// Test that the middleware allows access to users with one of multiple required roles
test('should allow access to users with one of multiple required roles', () => {
const mockReq = {
2026-03-17 07:07:36 +00:00
user: mockUserWithRole('moderator')
};
const mockRes = {
2026-03-17 07:07:36 +00:00
status: jest.fn().mockReturnThis(),
json: jest.fn()
};
const mockNext = jest.fn();
2026-03-17 07:07:36 +00:00
const middleware = requireRole(['admin', 'moderator']);
middleware(mockReq, mockRes, mockNext);
2026-03-17 07:07:36 +00:00
expect(mockNext).toHaveBeenCalled();
});
});