-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcore.unit.tests.js
More file actions
441 lines (376 loc) · 15.8 KB
/
Copy pathcore.unit.tests.js
File metadata and controls
441 lines (376 loc) · 15.8 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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/**
* Module dependencies.
*/
import _ from 'lodash';
import path from 'path';
import { jest } from '@jest/globals';
import assets from '../../../config/assets.js';
import config from '../../../config/index.js';
import configHelper from '../../../lib/helpers/config.js';
import logger from '../../../lib/services/logger.js';
import mongooseService from '../../../lib/services/mongoose.js';
import expressService from '../../../lib/services/express.js';
import errors from '../../../lib/helpers/errors.js';
import responses from '../../../lib/helpers/responses.js';
import AppError from '../../../lib/helpers/AppError.js';
import policy from '../../../lib/middlewares/policy.js';
/**
* Unit tests
*/
describe('Core unit tests:', () => {
let userFromSeedConfig;
let adminFromSeedConfig;
let tasksFromSeedConfig;
let originalLogConfig;
describe('Configurations', () => {
it('config generator should return an array of globbed paths', async () => {
const globPatterns = ['test/**/*.js'];
const result = await configHelper.getGlobbedPaths(globPatterns);
expect(Array.isArray(result)).toBe(true);
});
it('config generator should log a warning if config.domain is not set', () => {
const consoleSpy = jest.spyOn(console, 'log');
const config = { domain: null };
configHelper.validateDomainIsSet(config);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Important warning: config.domain is empty'));
consoleSpy.mockRestore();
});
it('config generator should return an object with files', async () => {
const assets = {
allYaml: 'test/**/*.yaml',
mongooseModels: 'test/**/*.model.js',
sequelizeModels: 'test/**/*.model.js',
routes: 'test/**/*.routes.js',
config: 'test/**/*.config.js',
policies: 'test/**/*.policies.js',
};
const result = await configHelper.initGlobalConfigFiles(assets);
expect(typeof result).toBe('object');
});
it('assets should contain the correct keys', () => {
const expectedKeys = ['allJS', 'allYaml', 'mongooseModels', 'sequelizeModels', 'routes', 'config', 'policies'];
expectedKeys.forEach((key) => {
expect(assets).toHaveProperty(key);
});
});
it('config should load production configuration in production env', async () => {
try {
const defaultConfig = (await import(path.join(process.cwd(), './config', 'defaults', 'production.js'))) || {};
expect(defaultConfig.default.app.title.split(' - ')[1]).toBe('Production Environment');
} catch (err) {
console.log(err);
expect(err).toBeFalsy();
}
});
});
describe('SeedDB', () => {
beforeAll((done) => {
userFromSeedConfig = config.seedDB.options.seedUser;
adminFromSeedConfig = config.seedDB.options.seedAdmin;
tasksFromSeedConfig = config.seedDB.options.seedTasks;
done();
});
it('should have seedDB configuration set for user', (done) => {
expect(userFromSeedConfig).toBeInstanceOf(Object);
expect(typeof userFromSeedConfig.email).toBe('string');
done();
});
it('should have seedDB configuration set for admin user', (done) => {
expect(userFromSeedConfig).toBeInstanceOf(Object);
expect(typeof adminFromSeedConfig.email).toBe('string');
done();
});
it('should have seedDB configuration set for tasks', (done) => {
expect(tasksFromSeedConfig).toBeInstanceOf(Array);
expect(typeof tasksFromSeedConfig[0].title).toBe('string');
expect(typeof tasksFromSeedConfig[1].title).toBe('string');
done();
});
});
describe('Logger', () => {
beforeEach(() => {
originalLogConfig = _.clone(config.log, true);
});
afterEach(() => {
config.log = originalLogConfig;
});
it('should retrieve the log format from the logger configuration', () => {
config.log = {
format: 'tiny',
};
const format = logger.getLogFormat();
expect(format).toBe('tiny');
});
it('should retrieve the log options from the logger configuration for a valid stream object', () => {
const options = logger.getMorganOptions();
expect(options).toBeInstanceOf(Object);
expect(options.stream).toBeDefined();
});
it('should use the default log format of "combined" when an invalid format was provided', async () => {
// manually set the config log format to be invalid
config.log = {
format: '_some_invalid_format_',
};
const format = logger.getLogFormat();
expect(format).toBe('combined');
});
it('should verify that a file logger object was created using the logger configuration', () => {
const _dir = process.cwd();
const _filename = 'unit-test-access.log';
config.log = {
fileLogger: {
directoryPath: _dir,
fileName: _filename,
},
};
const fileTransport = logger.getLogOptions(config);
expect(fileTransport).toBeInstanceOf(Object);
expect(fileTransport.filename).toBe(`${_dir}/${_filename}`);
});
it('should not create a file transport object if critical options are missing: filename', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
config.log = {
format: 'combined',
options: {
stream: {
directoryPath: process.cwd(),
fileName: '',
},
},
};
const fileTransport = logger.setupFileLogger(config);
expect(fileTransport).toBe(false);
consoleSpy.mockRestore();
});
it('should not create a file transport object if critical options are missing: directory', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
config.log = {
format: 'combined',
options: {
stream: {
directoryPath: '',
fileName: 'app.log',
},
},
};
const fileTransport = logger.setupFileLogger(config);
expect(fileTransport).toBe(false);
consoleSpy.mockRestore();
});
});
describe('Multer', () => {
it('should be able to get multer avatar configuration', () => {
const userAvatarConfig = config.uploads.avatar;
expect(userAvatarConfig).toBeDefined();
expect(userAvatarConfig.formats).toBeInstanceOf(Array);
expect(userAvatarConfig.limits.fileSize).toBe(52428.8);
});
});
describe('Errors', () => {
it('should return errors message properly', async () => {
try {
const fromCode = errors.getMessage({ code: 11001, errmsg: 'test' });
expect(fromCode).toBe('Test already exists.');
const fromCode2 = errors.getMessage({ code: 11001, errmsg: 'test.$.test' });
expect(fromCode2).toBe('Test.$ already exists.');
const fromCodeUnknow = errors.getMessage({ code: 'unknow' });
expect(fromCodeUnknow).toBe('Something went wrong.');
const fromErrorsArray = errors.getMessage({ errors: [{ message: 'error1' }, { message: 'error2' }] });
expect(fromErrorsArray).toBe('error1 error2 .');
const fromErrorsObject = errors.getMessage({ errors: { one: { message: 'error1' }, two: { message: 'error2' } } });
expect(fromErrorsObject).toBe('error1 error2 .');
const fromMessage = errors.getMessage({ message: 'error1' });
expect(fromMessage).toBe('error1.');
const fromEmpty = errors.getMessage({});
expect(fromEmpty).toBe('Something went wrong.');
} catch (err) {
console.log(err);
expect(err).toBeFalsy();
}
});
it('should sanitize unknown errors message', () => {
const fromUnknown = errors.getMessage({ random: 'value' });
expect(fromUnknown).toBe('Something went wrong.');
});
});
describe('Responses', () => {
it('should return explicit status and domain code in error response', () => {
const mockRes = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
const err = new AppError('Schema validation error', {
status: 422,
code: 'VALIDATION_ERROR',
details: { message: 'First name is required.' },
});
const result = responses.error(mockRes)(err);
expect(mockRes.status).toHaveBeenCalledWith(422);
expect(result.type).toBe('error');
expect(result.status).toBe(422);
expect(result.code).toBe(422);
expect(result.errorCode).toBe('VALIDATION_ERROR');
expect(result.description).toBe('First name is required.');
});
it('should not expose raw error payload in production mode', () => {
const originalNodeEnv = process.env.NODE_ENV;
try {
process.env.NODE_ENV = 'production';
const mockRes = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
const result = responses.error(mockRes, 422, 'Schema validation error', 'Invalid payload')({
details: { internal: 'secret' },
});
expect(result.error).toBeUndefined();
} finally {
process.env.NODE_ENV = originalNodeEnv;
}
});
});
describe('Config helpers', () => {
it('should return URL as-is when globPattern is a URL', async () => {
const result = await configHelper.getGlobbedPaths('http://example.com/resource');
expect(result).toContain('http://example.com/resource');
});
it('should apply string excludes when provided to getGlobbedPaths', async () => {
const result = await configHelper.getGlobbedPaths('modules/core/tests/*.js', 'modules/core/tests/');
expect(Array.isArray(result)).toBe(true);
});
it('should log a warning and disable ssl when cert files are missing', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
const fakeConfig = { secure: { ssl: true, key: './nonexistent.pem', cert: './nonexistent2.pem' } };
configHelper.initSecureMode(fakeConfig);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Certificate file'));
expect(fakeConfig.secure.ssl).toBe(false);
consoleSpy.mockRestore();
});
it('should return true early when ssl is not configured', () => {
const result = configHelper.initSecureMode({ secure: { ssl: false } });
expect(result).toBe(true);
});
});
describe('Express service', () => {
it('should set app.locals.secure when ssl is enabled', () => {
const originalSecure = config.secure;
config.secure = { ssl: true };
const mockApp = { locals: {}, use: jest.fn() };
expressService.initLocalVariables(mockApp);
expect(mockApp.locals.secure).toBe(true);
config.secure = originalSecure;
});
it('should not set app.locals.secure when ssl is disabled', () => {
const originalSecure = config.secure;
config.secure = { ssl: false };
const mockApp = { locals: {}, use: jest.fn() };
expressService.initLocalVariables(mockApp);
expect(mockApp.locals.secure).toBeUndefined();
config.secure = originalSecure;
});
it('should call next() when error middleware receives no error', () => {
const mockApp = { use: jest.fn() };
expressService.initErrorRoutes(mockApp);
const middleware = mockApp.use.mock.calls[0][0];
const mockNext = jest.fn();
const mockRes = { status: jest.fn().mockReturnThis(), send: jest.fn() };
middleware(null, {}, mockRes, mockNext);
expect(mockNext).toHaveBeenCalled();
});
it('should respond with 500 when error has no status code', () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
const mockApp = { use: jest.fn() };
expressService.initErrorRoutes(mockApp);
const middleware = mockApp.use.mock.calls[0][0];
const mockNext = jest.fn();
const mockSend = jest.fn();
const mockStatus = jest.fn().mockReturnValue({ send: mockSend });
const mockRes = { status: mockStatus };
const err = new Error('test error');
middleware(err, {}, mockRes, mockNext);
expect(mockStatus).toHaveBeenCalledWith(500);
consoleSpy.mockRestore();
});
it('should respond with the error status code when provided', () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
const mockApp = { use: jest.fn() };
expressService.initErrorRoutes(mockApp);
const middleware = mockApp.use.mock.calls[0][0];
const mockSend = jest.fn();
const mockStatus = jest.fn().mockReturnValue({ send: mockSend });
const mockRes = { status: mockStatus };
const err = new Error('not found');
err.status = 404;
middleware(err, {}, mockRes, jest.fn());
expect(mockStatus).toHaveBeenCalledWith(404);
consoleSpy.mockRestore();
});
});
describe('Policy', () => {
beforeAll(async () => {
const [homePolicy, tasksPolicy, uploadsPolicy, usersAccountPolicy, usersAdminPolicy] = await Promise.all([
import('../../../modules/home/policies/home.policy.js'),
import('../../../modules/tasks/policies/tasks.policy.js'),
import('../../../modules/uploads/policies/uploads.policy.js'),
import('../../../modules/users/policies/users.account.policy.js'),
import('../../../modules/users/policies/users.admin.policy.js'),
]);
homePolicy.default.invokeRolesPolicies();
tasksPolicy.default.invokeRolesPolicies();
uploadsPolicy.default.invokeRolesPolicies();
usersAccountPolicy.default.invokeRolesPolicies();
usersAdminPolicy.default.invokeRolesPolicies();
});
it('guest can read public task routes', async () => {
const ability = await policy.defineAbilityFor(null);
expect(ability.can('read', '/api/tasks')).toBe(true);
});
it('guest cannot create tasks', async () => {
const ability = await policy.defineAbilityFor(null);
expect(ability.can('create', '/api/tasks')).toBe(false);
});
it('user can manage tasks', async () => {
const ability = await policy.defineAbilityFor({ roles: ['user'] });
expect(ability.can('create', '/api/tasks')).toBe(true);
});
it('user cannot access admin routes', async () => {
const ability = await policy.defineAbilityFor({ roles: ['user'] });
expect(ability.can('read', '/api/users')).toBe(false);
});
it('admin can access admin routes', async () => {
const ability = await policy.defineAbilityFor({ roles: ['admin'] });
expect(ability.can('read', '/api/users')).toBe(true);
});
});
describe('Mongoose service', () => {
it('should invoke callback after loading models', async () => {
const callback = jest.fn();
await mongooseService.loadModels(callback);
expect(callback).toHaveBeenCalled();
});
});
describe('Auth service', () => {
let AuthService;
beforeAll(async () => {
AuthService = (await import(path.resolve('./modules/auth/services/auth.service.js'))).default;
});
it('should return null when removeSensitive is called with a non-object', () => {
expect(AuthService.removeSensitive(null)).toBeNull();
expect(AuthService.removeSensitive('string')).toBeNull();
expect(AuthService.removeSensitive(undefined)).toBeNull();
});
it('should return picked fields when removeSensitive is called with a valid user', () => {
const fakeUser = { id: '1', email: 'a@b.com', password: 'secret', firstName: 'A' };
const result = AuthService.removeSensitive(fakeUser);
expect(result).toBeDefined();
expect(result.password).toBeUndefined();
});
it('should throw when checkPassword is called with a weak password', () => {
expect(() => AuthService.checkPassword('password')).toThrow();
});
it('should return the password when checkPassword is called with a strong password', () => {
const strong = 'C0rr3ct!H0rs3B@tt3ry';
expect(AuthService.checkPassword(strong)).toBe(strong);
});
});
});