-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.test.js
More file actions
87 lines (75 loc) · 2.75 KB
/
auth.test.js
File metadata and controls
87 lines (75 loc) · 2.75 KB
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
import request from 'supertest';
import app from '../src/app.js';
import User from '../src/models/User.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { jest } from '@jest/globals';
jest.setTimeout(30000);
jest.mock('../src/models/User.js');
jest.mock('bcrypt');
describe('Auth Integration Tests', () => {
beforeEach(() => {
jest.clearAllMocks();
process.env.JWT_SECRET = 'testsecret';
});
describe('POST /api/auth/login', () => {
it('should return 400 if email or password is missing', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({ email: 'test@test.com' }); // missing password
expect(res.statusCode).toBe(400);
expect(res.body.success).toBe(false);
});
it('should return 401 for invalid email', async () => {
User.findOne = jest.fn().mockReturnValue({
select: jest.fn().mockResolvedValue(null)
});
const res = await request(app)
.post('/api/auth/login')
.send({ email: 'test@test.com', password: 'password', role: 'admin' });
expect(res.statusCode).toBe(401);
expect(res.body.message).toMatch(/Invalid role or email/i);
});
it('should return 200 and token for valid credentials', async () => {
const mockUser = {
_id: 'userid',
email: 'admin@test.com',
role: 'admin',
status: 'Active'
};
User.findOne = jest.fn().mockReturnValue({
select: jest.fn().mockResolvedValue(mockUser)
});
bcrypt.compare = jest.fn().mockResolvedValue(true);
const res = await request(app)
.post('/api/auth/login')
.send({ email: 'admin@test.com', password: 'password', role: 'admin' });
expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.token).toBeDefined();
expect(res.body.user.email).toBe('admin@test.com');
});
});
describe('GET /api/auth/me', () => {
it('should return 401 if no token provided', async () => {
const res = await request(app).get('/api/auth/me');
expect(res.statusCode).toBe(401);
});
it('should return user profile if valid token provided', async () => {
const token = jwt.sign({ id: 'userid' }, process.env.JWT_SECRET);
const mockUser = {
_id: 'userid',
email: 'admin@test.com',
role: 'admin',
status: 'Active',
};
User.findById = jest.fn().mockReturnValue({ select: jest.fn().mockResolvedValue(mockUser) });
const res = await request(app)
.get('/api/auth/me')
.set('Authorization', `Bearer ${token}`);
expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.data.email).toBe('admin@test.com');
});
});
});