Spaces:
Paused
Paused
File size: 9,497 Bytes
e6664ed 2986397 e6664ed 2986397 e6664ed 2986397 e6664ed 2986397 e6664ed 5b9f147 e6664ed 5b9f147 e6664ed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | 'use strict';
/**
* Auth Controller Unit Tests
* Tests for user authentication endpoints
*/
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
process.env.JWT_SECRET = 'test-secret-for-unit-tests';
// Mock dependencies before requiring the controller
const mockPool = {
query: jest.fn(),
connect: jest.fn(() => ({
query: jest.fn(),
release: jest.fn()
}))
};
jest.mock('../db', () => ({
getPool: jest.fn(() => mockPool)
}));
jest.mock('../services/google.service', () => ({
verifyToken: jest.fn()
}));
// Now require the controller
const authController = require('../controllers/auth.controller');
const { getPool } = require('../db');
describe('Auth Controller', () => {
let mockReq;
let mockRes;
let mockPool;
beforeEach(() => {
mockReq = {
body: {},
user: {},
headers: {}
};
mockRes = {
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis()
};
mockPool = getPool();
jest.clearAllMocks();
});
describe('register', () => {
it('should return 400 if email already exists', async () => {
mockReq.body = {
email: 'existing@example.com',
password: 'Password123!',
name: 'Test User'
};
mockPool.query.mockResolvedValueOnce({ rows: [{ id: 'existing-id' }] });
await authController.register(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(400);
expect(mockRes.json).toHaveBeenCalledWith({ error: 'Email already registered' });
});
it('should successfully register a new user', async () => {
mockReq.body = {
email: 'newuser@example.com',
password: 'SecurePass123!',
name: 'New User'
};
// User doesn't exist
mockPool.query.mockResolvedValueOnce({ rows: [] });
// Insert user returns new user
const newUser = {
id: 'new-user-id',
email: 'newuser@example.com',
name: 'New User',
role: 'tourist'
};
mockPool.query.mockResolvedValueOnce({ rows: [newUser] });
await authController.register(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(201);
expect(mockRes.json).toHaveBeenCalledWith(
expect.objectContaining({
user: expect.objectContaining({
email: 'newuser@example.com'
}),
tokens: expect.objectContaining({
accessToken: expect.any(String),
refreshToken: expect.any(String)
})
})
);
});
it('should return 500 on database error', async () => {
mockReq.body = { email: 'test@test.com', password: 'pass', name: 'Test' };
mockPool.query.mockRejectedValueOnce(new Error('Database error'));
await authController.register(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(500);
});
});
describe('login', () => {
it('should return 401 for non-existent user', async () => {
mockReq.body = {
email: 'nonexistent@example.com',
password: 'password123'
};
mockPool.query.mockResolvedValueOnce({ rows: [] });
await authController.login(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(401);
expect(mockRes.json).toHaveBeenCalledWith({ error: 'Invalid credentials' });
});
it('should return 401 for invalid password', async () => {
mockReq.body = {
email: 'user@example.com',
password: 'wrongpassword'
};
// User exists with different password
const user = {
id: 'user-id',
email: 'user@example.com',
password_hash: await bcrypt.hash('correctpassword', 10),
is_active: true
};
mockPool.query.mockResolvedValueOnce({ rows: [user] });
await authController.login(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(401);
});
it('should successfully login with valid credentials', async () => {
const password = 'ValidPassword123!';
const hashedPassword = await bcrypt.hash(password, 10);
mockReq.body = {
email: 'user@example.com',
password: password
};
const user = {
id: 'user-id',
email: 'user@example.com',
password_hash: hashedPassword,
name: 'Test User',
role: 'tourist',
is_active: true
};
mockPool.query.mockResolvedValueOnce({ rows: [user] });
await authController.login(mockReq, mockRes);
expect(mockRes.json).toHaveBeenCalledWith(
expect.objectContaining({
user: expect.objectContaining({
email: 'user@example.com'
}),
tokens: expect.objectContaining({
accessToken: expect.any(String),
refreshToken: expect.any(String)
})
})
);
});
});
describe('currentUser', () => {
it('should return current user info', async () => {
mockReq.user = {
id: 'user-id',
email: 'user@example.com',
role: 'tourist'
};
const fullUser = {
id: 'user-id',
email: 'user@example.com',
name: 'Test User',
role: 'tourist'
};
mockPool.query.mockResolvedValueOnce({ rows: [fullUser] });
await authController.currentUser(mockReq, mockRes);
expect(mockRes.json).toHaveBeenCalledWith(
expect.objectContaining({
user: expect.objectContaining({
email: 'user@example.com'
})
})
);
});
it('should return 404 if user not found', async () => {
mockReq.user = { id: 'nonexistent-id' };
mockPool.query.mockResolvedValueOnce({ rows: [] });
await authController.currentUser(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(404);
});
});
describe('logout', () => {
it('should return success message', async () => {
await authController.logout(mockReq, mockRes);
expect(mockRes.json).toHaveBeenCalledWith({
success: true,
message: 'Logged out successfully'
});
});
});
describe('refresh', () => {
it('should return 401 for invalid refresh token', async () => {
mockReq.body = { refreshToken: 'invalid-token' };
await authController.refresh(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(401);
});
it('should return 401 for token without refresh type', async () => {
// Create a token without type: 'refresh'
const invalidToken = jwt.sign({ id: 'user-id' }, process.env.JWT_SECRET, { expiresIn: '1h' });
mockReq.body = { refreshToken: invalidToken };
await authController.refresh(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(401);
});
it('should refresh tokens successfully with valid refresh token', async () => {
// Create a valid refresh token
const validRefreshToken = jwt.sign(
{ id: 'user-id', type: 'refresh' },
process.env.JWT_SECRET,
{ expiresIn: '30d' }
);
mockReq.body = { refreshToken: validRefreshToken };
const user = { id: 'user-id', email: 'user@test.com', name: 'Test', role: 'tourist' };
mockPool.query.mockResolvedValueOnce({ rows: [user] });
await authController.refresh(mockReq, mockRes);
expect(mockRes.json).toHaveBeenCalledWith(
expect.objectContaining({
user: expect.objectContaining({ email: 'user@test.com' }),
tokens: expect.objectContaining({
accessToken: expect.any(String),
refreshToken: expect.any(String)
})
})
);
});
});
describe('changePassword', () => {
it('should return 400 if passwords missing', async () => {
mockReq.user = { id: 'user-id' };
mockReq.body = {};
await authController.changePassword(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(400);
});
it('should return 401 if current password is incorrect', async () => {
mockReq.user = { id: 'user-id' };
mockReq.body = {
currentPassword: 'wrongpassword',
newPassword: 'NewSecurePass123!'
};
const user = {
id: 'user-id',
password_hash: await bcrypt.hash('correctpassword', 10)
};
mockPool.query.mockResolvedValueOnce({ rows: [user] });
await authController.changePassword(mockReq, mockRes);
expect(mockRes.status).toHaveBeenCalledWith(401);
});
it('should successfully change password with correct current password', async () => {
const currentPassword = 'CurrentPass123!';
mockReq.user = { id: 'user-id' };
mockReq.body = {
currentPassword: currentPassword,
newPassword: 'NewSecurePass123!'
};
const user = {
id: 'user-id',
password_hash: await bcrypt.hash(currentPassword, 10)
};
mockPool.query.mockResolvedValueOnce({ rows: [user] });
mockPool.query.mockResolvedValueOnce({}); // UPDATE query
await authController.changePassword(mockReq, mockRes);
expect(mockRes.json).toHaveBeenCalledWith({
success: true,
message: 'Password changed successfully'
});
});
});
});
|