forked from mtusi2026/mtusi2026lab3
70 lines
2.4 KiB
TypeScript
70 lines
2.4 KiB
TypeScript
import { INestApplication } from '@nestjs/common';
|
|
import Ajv2020 from 'ajv/dist/2020';
|
|
import request from 'supertest';
|
|
import { OPERATION_EXAMPLES } from '../src/docs/examples';
|
|
import { loadDocument, setupSwagger } from '../src/docs/swagger';
|
|
import { createTestApp } from './helpers';
|
|
|
|
const CONTRACT_ID = 'https://contract.local/openapi.json';
|
|
|
|
describe('Swagger UI и примеры (e2e)', () => {
|
|
let app: INestApplication;
|
|
let server: any;
|
|
|
|
beforeAll(async () => {
|
|
({ app, server } = await createTestApp({}, setupSwagger));
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await app.close();
|
|
});
|
|
|
|
it('отдаёт Swagger UI и документ контракта со всеми путями', async () => {
|
|
await request(server).get('/docs').expect(200);
|
|
const res = await request(server).get('/docs-json').expect(200);
|
|
expect(res.body.openapi).toBe('3.1.0');
|
|
expect(Object.keys(res.body.paths)).toEqual(
|
|
Object.keys(loadDocument().paths),
|
|
);
|
|
expect(res.body.components.securitySchemes).toHaveProperty('basicAuth');
|
|
expect(res.body.components.securitySchemes).toHaveProperty('bearerAuth');
|
|
});
|
|
|
|
it('каждый пример запроса и ответа проходит JSON Schema контракта', () => {
|
|
const document: any = loadDocument();
|
|
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
|
ajv.addSchema(document, CONTRACT_ID);
|
|
let checked = 0;
|
|
for (const [key, examples] of Object.entries(OPERATION_EXAMPLES)) {
|
|
const [method, path] = key.split(' ');
|
|
const operation = document.paths[path][method.toLowerCase()];
|
|
const targets: [string, any, Record<string, any>][] = [];
|
|
if (examples.request) {
|
|
targets.push([
|
|
'request',
|
|
operation.requestBody.content['application/json'].schema,
|
|
examples.request,
|
|
]);
|
|
}
|
|
for (const [status, named] of Object.entries(examples.responses)) {
|
|
targets.push([
|
|
status,
|
|
operation.responses[status].content['application/json'].schema,
|
|
named,
|
|
]);
|
|
}
|
|
for (const [where, schema, named] of targets) {
|
|
const validate = ajv.compile({ $ref: CONTRACT_ID + schema.$ref });
|
|
for (const [name, example] of Object.entries(named)) {
|
|
const valid = validate(example.value);
|
|
expect({ key, where, name, valid, errors: validate.errors }).toEqual(
|
|
{ key, where, name, valid: true, errors: null },
|
|
);
|
|
checked++;
|
|
}
|
|
}
|
|
}
|
|
expect(checked).toBeGreaterThan(40);
|
|
});
|
|
});
|