-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathexpress.docs.unit.tests.js
More file actions
436 lines (380 loc) · 14.7 KB
/
express.docs.unit.tests.js
File metadata and controls
436 lines (380 loc) · 14.7 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
/**
* Module dependencies.
*/
import { jest, beforeEach, afterEach, describe, test, expect } from '@jest/globals';
/**
* Unit tests for core/doc/index.yml OpenAPI baseline — bearerAuth description,
* apiKeyAuth alias, SuccessResponse + ErrorResponse schema descriptions.
* (T13 Fix B — infra#38)
*/
describe('express initSwagger — core/doc/index.yml OpenAPI baseline (T13 Fix B):', () => {
const mockCoreYamlDoc = {
openapi: '3.0.0',
info: { version: '1.0.0' },
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
description: 'Authenticate by sending an HTTP `Authorization: Bearer <token>` header.',
},
apiKeyAuth: {
type: 'http',
scheme: 'bearer',
description: 'Legacy alias for `bearerAuth`. New integrations should use `bearerAuth`.',
},
},
schemas: {
SuccessResponse: {
type: 'object',
description: 'Standard success envelope. data type varies by endpoint.',
properties: {
type: { type: 'string', enum: ['success'] },
message: { type: 'string' },
data: { description: 'Response payload (type varies by endpoint)' },
},
},
ErrorResponse: {
type: 'object',
description: 'Standard error envelope returned on 4xx/5xx.',
properties: {
type: { type: 'string', enum: ['error'] },
message: { type: 'string' },
code: { type: 'integer' },
status: { type: 'integer' },
errorCode: { type: 'string' },
description: { type: 'string' },
error: { type: 'string', description: 'JSON-stringified error details included only in non-production environments.' },
},
},
},
},
};
const baseConfig = {
swagger: { enable: true },
files: { swagger: ['/fake/core.yaml'], guides: [] },
app: { title: 'Test API', description: 'Test', url: 'https://example.com' },
domain: 'https://example.com',
};
const buildMockApp = () => {
const routes = {};
return { get: (path, handler) => { routes[path] = handler; }, _routes: routes };
};
const callSpecRoute = (app) => {
const handler = app._routes['/api/spec.json'];
if (!handler) throw new Error('/api/spec.json route not registered');
let spec = null;
const res = { json: (body) => { spec = body; } };
handler({}, res);
return spec;
};
beforeEach(() => {
jest.resetModules();
jest.unstable_mockModule('fs', () => ({
default: { readFileSync: jest.fn().mockReturnValue('mocked') },
readFileSync: jest.fn().mockReturnValue('mocked'),
}));
jest.unstable_mockModule('js-yaml', () => ({
default: { load: jest.fn().mockReturnValue(mockCoreYamlDoc) },
load: jest.fn().mockReturnValue(mockCoreYamlDoc),
}));
jest.unstable_mockModule('../../helpers/guides.js', () => ({
default: { loadGuides: jest.fn().mockReturnValue([]), mergeGuidesIntoSpec: jest.fn() },
}));
jest.unstable_mockModule('../logger.js', () => ({
default: { warn: jest.fn(), info: jest.fn(), error: jest.fn() },
}));
});
afterEach(() => jest.restoreAllMocks());
test('bearerAuth security scheme exists in merged spec', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({ default: baseConfig }));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
const spec = callSpecRoute(app);
expect(spec.components.securitySchemes.bearerAuth).toBeDefined();
});
test('bearerAuth has a description field', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({ default: baseConfig }));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
const spec = callSpecRoute(app);
expect(typeof spec.components.securitySchemes.bearerAuth.description).toBe('string');
expect(spec.components.securitySchemes.bearerAuth.description.length).toBeGreaterThan(0);
});
test('apiKeyAuth security scheme exists as legacy alias', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({ default: baseConfig }));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
const spec = callSpecRoute(app);
expect(spec.components.securitySchemes.apiKeyAuth).toBeDefined();
});
test('apiKeyAuth description mentions bearerAuth as the canonical scheme', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({ default: baseConfig }));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
const spec = callSpecRoute(app);
expect(spec.components.securitySchemes.apiKeyAuth.description).toMatch(/bearerAuth/i);
});
test('SuccessResponse schema has a description', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({ default: baseConfig }));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
const spec = callSpecRoute(app);
expect(typeof spec.components.schemas.SuccessResponse.description).toBe('string');
expect(spec.components.schemas.SuccessResponse.description.length).toBeGreaterThan(0);
});
test('ErrorResponse schema has a description', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({ default: baseConfig }));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
const spec = callSpecRoute(app);
expect(typeof spec.components.schemas.ErrorResponse.description).toBe('string');
expect(spec.components.schemas.ErrorResponse.description.length).toBeGreaterThan(0);
});
});
/**
* Unit tests for express.js initSwagger — Redoc theme polish (issue #3686).
*
* Two scenarios:
* 1. Default theme markers (Inter + JetBrains Mono) appear in served HTML.
* 2. config.docs.redocTheme deep-merge override (e.g. primary color) reaches served HTML.
*/
describe('express initSwagger — Redoc theme (issue #3686):', () => {
let capturedHtml;
const mockYamlDoc = {
openapi: '3.0.0',
info: { title: 'Test API', version: '1.0.0', description: 'Test' },
paths: {},
};
const baseConfig = {
swagger: { enable: true },
files: { swagger: ['/fake/swagger.yaml'], guides: [] },
app: { title: 'Test API', description: 'Test', url: 'https://example.com' },
domain: 'https://example.com',
};
/**
* Build a mock Express app that captures responses for /api/docs and /api/spec.json
*/
const buildMockApp = () => {
const routes = {};
const app = {
get: (path, handler) => {
routes[path] = handler;
},
_routes: routes,
};
return app;
};
/**
* Trigger the /api/docs route and capture the HTML sent
*/
const callDocsRoute = (app) => {
const handler = app._routes['/api/docs'];
if (!handler) throw new Error('/api/docs route not registered');
let html = null;
const res = {
type: jest.fn(),
send: (body) => {
html = body;
},
};
handler({}, res);
return html;
};
/**
* Trigger the /api/spec.json route and capture the JSON spec served
*/
const callSpecRoute = (app) => {
const handler = app._routes['/api/spec.json'];
if (!handler) throw new Error('/api/spec.json route not registered');
let spec = null;
const res = { json: (body) => { spec = body; } };
handler({}, res);
return spec;
};
beforeEach(() => {
jest.resetModules();
capturedHtml = null;
// Mock fs + js-yaml so we don't need a real YAML file
jest.unstable_mockModule('fs', () => ({
default: { readFileSync: jest.fn().mockReturnValue('mocked') },
readFileSync: jest.fn().mockReturnValue('mocked'),
}));
jest.unstable_mockModule('js-yaml', () => ({
default: { load: jest.fn().mockReturnValue(mockYamlDoc) },
load: jest.fn().mockReturnValue(mockYamlDoc),
}));
// Mock guides helper — no guides
jest.unstable_mockModule('../../helpers/guides.js', () => ({
default: {
loadGuides: jest.fn().mockReturnValue([]),
mergeGuidesIntoSpec: jest.fn(),
},
}));
// Mock logger
jest.unstable_mockModule('../logger.js', () => ({
default: { warn: jest.fn(), info: jest.fn(), error: jest.fn() },
}));
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('default theme (no config.docs override):', () => {
test('should include Inter font family in serialised Redoc options', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: baseConfig,
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
capturedHtml = callDocsRoute(app);
expect(capturedHtml).toContain('Inter');
});
test('should include JetBrains Mono in serialised Redoc options', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: baseConfig,
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
capturedHtml = callDocsRoute(app);
expect(capturedHtml).toContain('JetBrains Mono');
});
test('should include tighter sidebar width (260px) in serialised Redoc options', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: baseConfig,
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
capturedHtml = callDocsRoute(app);
expect(capturedHtml).toContain('260px');
});
test('should include dark right panel background (#1a1a1a) in serialised Redoc options', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: baseConfig,
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
capturedHtml = callDocsRoute(app);
expect(capturedHtml).toContain('#1a1a1a');
});
test('should inject x-logo href in spec when config.app.url is set', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: { ...baseConfig },
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
const spec = callSpecRoute(app);
// x-logo is added to spec.info when config.app.url is present
expect(spec.info['x-logo']).toBeDefined();
expect(spec.info['x-logo'].href).toBe('https://example.com');
});
test('should inject x-logo url in spec when config.app.logo is provided', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
...baseConfig,
app: { ...baseConfig.app, logo: 'https://example.com/logo.png' },
},
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
const spec = callSpecRoute(app);
expect(spec.info['x-logo'].url).toBe('https://example.com/logo.png');
});
test('should not inject x-logo when config.app.url is absent', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
...baseConfig,
app: { title: 'Test API', description: 'Test' }, // no url
},
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
// Must not throw and no x-logo in spec
expect(() => expressService.initSwagger(app)).not.toThrow();
const spec = callSpecRoute(app);
expect(spec.info['x-logo']).toBeUndefined();
});
});
describe('config.docs.redocTheme deep-merge override:', () => {
test('should apply custom primary color from config.docs.redocTheme override', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
...baseConfig,
docs: {
redocTheme: {
colors: { primary: { main: '#ff0000' } },
},
},
},
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
capturedHtml = callDocsRoute(app);
// Override color reaches the HTML
expect(capturedHtml).toContain('#ff0000');
});
test('should preserve default font family when override adds a color', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
...baseConfig,
docs: {
redocTheme: {
colors: { primary: { main: '#00ff00' } },
},
},
},
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
capturedHtml = callDocsRoute(app);
// Default font must still be present even when an override is applied
expect(capturedHtml).toContain('Inter');
expect(capturedHtml).toContain('#00ff00');
});
test('should allow override to replace sidebar width', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
...baseConfig,
docs: {
redocTheme: {
sidebar: { width: '300px' },
},
},
},
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
capturedHtml = callDocsRoute(app);
expect(capturedHtml).toContain('300px');
});
test('should apply devkit defaults when config.docs is absent', async () => {
jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
...baseConfig,
// no docs key at all
},
}));
const { default: expressService } = await import('../express.js');
const app = buildMockApp();
expressService.initSwagger(app);
capturedHtml = callDocsRoute(app);
expect(capturedHtml).toContain('Inter');
expect(capturedHtml).toContain('JetBrains Mono');
});
});
});