Phase 1: Backend skeleton (Express, MongoDB, config, error middleware, health)
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Инициализация тестового окружения.
|
||||
*
|
||||
* Задаёт переменные окружения до импорта модулей приложения
|
||||
* (env.ts читает process.env при первой загрузке).
|
||||
*/
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.MONGODB_URI = 'mongodb://127.0.0.1:27017/newsEditorTest';
|
||||
process.env.JWT_SECRET = 'test-secret';
|
||||
process.env.CLIENT_ORIGIN = 'http://localhost:5173';
|
||||
Reference in New Issue
Block a user