Files
news-editor/server/tests/health.test.ts
T

87 lines
3.2 KiB
TypeScript

import request from 'supertest';
import { describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js';
import { ApiError } from '../src/utils/ApiError.js';
import type { Request, RequestHandler, Response } from 'express';
/**
* Извлекает машиночитаемый код из тела ответа.
*
* @param body — тело ответа, сериализованное supertest
* @returns код ошибки (или undefined, если структура не совпадает)
*/
function errorCodeOf(body: unknown): string | undefined {
if (typeof body !== 'object' || body === null) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- извлечение полей из unknown
const error = (body as { error?: unknown }).error;
if (typeof error !== 'object' || error === null) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- извлечение полей из unknown
const code = (error as { code?: unknown }).code;
return typeof code === 'string' ? code : undefined;
}
/**
* Создаёт middleware, бросаемое ошибку для указанного пути.
*
* @param path — путь, для которого бросается ошибка
* @param error — ошибка, которую нужно бросить
* @returns middleware, готовое к подключению в createApp
*/
function throwingMiddleware(path: string, error: Error): RequestHandler {
return (req: Request, _res: Response, next) => {
if (req.path === path) {
throw error;
}
next();
};
}
/**
* Тесты базового каркаса API.
*/
describe('API skeleton', () => {
const app = createApp();
describe('GET /api/health', () => {
it('возвращает 200 и статус ok', async () => {
const res = await request(app).get('/api/health');
expect(res.status).toBe(200);
expect(res.body).toEqual({ status: 'ok' });
});
});
describe('неизвестные маршруты', () => {
it('возвращает 404 в едином формате ошибки', async () => {
const res = await request(app).get('/api/unknown');
expect(res.status).toBe(404);
expect(errorCodeOf(res.body)).toBe('NOT_FOUND');
});
});
describe('error middleware', () => {
it('обрабатывает ApiError с её статусом и кодом', async () => {
const errorApp = createApp(throwingMiddleware('/api/test-conflict', new ApiError(409, 'CONFLICT', 'Тестовый конфликт')));
const res = await request(errorApp).get('/api/test-conflict');
expect(res.status).toBe(409);
expect(res.body).toEqual({ error: { code: 'CONFLICT', message: 'Тестовый конфликт' } });
});
it('возвращает 500 для непредвиденных ошибок', async () => {
const errorApp = createApp(throwingMiddleware('/api/test-unexpected', new Error('Внутренний сбой')));
const res = await request(errorApp).get('/api/test-unexpected');
expect(res.status).toBe(500);
expect(errorCodeOf(res.body)).toBe('INTERNAL_ERROR');
});
});
});