-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestModels.js
More file actions
246 lines (206 loc) · 7.03 KB
/
testModels.js
File metadata and controls
246 lines (206 loc) · 7.03 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
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
/**
* Test script to verify Database Models
* Run this file to test Department and Employee models
*
* Usage: node testModels.js
*/
require('dotenv').config();
const mongoose = require('mongoose');
const { Department, Employee } = require('./models');
// Connect to MongoDB
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI);
console.log('✅ Connected to MongoDB');
} catch (error) {
console.error('❌ MongoDB connection error:', error.message);
process.exit(1);
}
};
// Test Department Model
const testDepartmentModel = async () => {
console.log('\n📊 Testing Department Model...\n');
try {
// Create a test department
const department = new Department({
name: 'IT Department',
description: 'Information Technology and Software Development'
});
await department.save();
console.log('✅ Department created successfully:');
console.log(JSON.stringify(department, null, 2));
// Find the department
const foundDept = await Department.findOne({ name: 'IT Department' });
console.log('\n✅ Department found:', foundDept.name);
// Test static method
const activeDepts = await Department.findActive();
console.log(`✅ Active departments count: ${activeDepts.length}`);
return department;
} catch (error) {
console.error('❌ Department test error:', error.message);
throw error;
}
};
// Test Employee Model
const testEmployeeModel = async (department) => {
console.log('\n👤 Testing Employee Model...\n');
try {
// Create a test employee
const employee = new Employee({
firstName: 'john',
lastName: 'doe',
email: 'john.doe@company.com',
phone: '123-456-7890',
jobTitle: 'Software Engineer',
department: department._id,
country: 'United States',
state: 'California',
city: 'San Francisco',
address: '123 Tech Street',
zipCode: '94102',
salary: 75000,
gender: 'Male'
});
await employee.save();
console.log('✅ Employee created successfully:');
console.log(JSON.stringify(employee, null, 2));
// Test virtual field
console.log('\n✅ Full Name (virtual):', employee.fullName);
// Find employee with populated department
const foundEmployee = await Employee.findById(employee._id)
.populate('department', 'name description');
console.log('✅ Employee found with department:',
foundEmployee.fullName,
'→',
foundEmployee.department.name
);
// Create a supervisor
const supervisor = new Employee({
firstName: 'jane',
lastName: 'smith',
email: 'jane.smith@company.com',
phone: '123-456-7891',
jobTitle: 'Senior Manager',
department: department._id,
country: 'United States',
state: 'California',
city: 'San Francisco',
salary: 95000,
gender: 'Female'
});
await supervisor.save();
console.log('\n✅ Supervisor created:', supervisor.fullName);
// Assign supervisor to employee
employee.supervisor = supervisor._id;
await employee.save();
console.log('✅ Supervisor assigned to employee');
// Test populated query
const employeeWithSupervisor = await Employee.findById(employee._id)
.populate('department', 'name')
.populate('supervisor', 'firstName lastName jobTitle');
console.log('\n✅ Employee with supervisor:');
console.log(` Employee: ${employeeWithSupervisor.fullName}`);
console.log(` Supervisor: ${employeeWithSupervisor.supervisor.firstName} ${employeeWithSupervisor.supervisor.lastName}`);
console.log(` Department: ${employeeWithSupervisor.department.name}`);
// Test static methods
const potentialSupervisors = await Employee.getPotentialSupervisors(employee._id);
console.log(`\n✅ Potential supervisors count: ${potentialSupervisors.length}`);
return { employee, supervisor };
} catch (error) {
console.error('❌ Employee test error:', error.message);
throw error;
}
};
// Test Relationships
const testRelationships = async (department) => {
console.log('\n🔗 Testing Relationships...\n');
try {
// Get employees in department
const deptEmployees = await Employee.findByDepartment(department._id);
console.log(`✅ Employees in ${department.name}: ${deptEmployees.length}`);
deptEmployees.forEach(emp => {
console.log(` - ${emp.fullName} (${emp.jobTitle})`);
if (emp.supervisor) {
console.log(` Supervisor: ${emp.supervisor.firstName} ${emp.supervisor.lastName}`);
}
});
// Update department employee count
department.employeeCount = deptEmployees.length;
await department.save();
console.log(`\n✅ Department employee count updated: ${department.employeeCount}`);
} catch (error) {
console.error('❌ Relationship test error:', error.message);
throw error;
}
};
// Test Validations
const testValidations = async () => {
console.log('\n✅ Testing Validations...\n');
try {
// Test invalid email
const invalidEmployee = new Employee({
firstName: 'Test',
lastName: 'User',
email: 'invalid-email', // Invalid email
phone: '123-456-7890',
jobTitle: 'Tester',
country: 'USA',
state: 'CA',
city: 'SF'
});
await invalidEmployee.save();
} catch (error) {
console.log('✅ Email validation working:', error.message);
}
try {
// Test missing required field
const incompleteEmployee = new Employee({
firstName: 'Test'
// Missing required fields
});
await incompleteEmployee.save();
} catch (error) {
console.log('✅ Required field validation working');
}
};
// Cleanup test data
const cleanup = async () => {
console.log('\n🧹 Cleaning up test data...\n');
try {
await Employee.deleteMany({
email: { $in: ['john.doe@company.com', 'jane.smith@company.com'] }
});
await Department.deleteMany({ name: 'IT Department' });
console.log('✅ Test data cleaned up');
} catch (error) {
console.error('❌ Cleanup error:', error.message);
}
};
// Main test function
const runTests = async () => {
console.log('🧪 Starting Model Tests...');
console.log('================================\n');
try {
await connectDB();
// Run tests
const department = await testDepartmentModel();
const { employee, supervisor } = await testEmployeeModel(department);
await testRelationships(department);
await testValidations();
console.log('\n================================');
console.log('✅ All tests completed successfully!');
console.log('================================\n');
// Cleanup
await cleanup();
// Close connection
await mongoose.connection.close();
console.log('✅ MongoDB connection closed');
} catch (error) {
console.error('\n❌ Test failed:', error);
await cleanup();
await mongoose.connection.close();
process.exit(1);
}
};
// Run tests
runTests();