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

197 lines
7.3 KiB
TypeScript

import request from 'supertest';
import { describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js';
import { verifyUserToken } from '../src/utils/jwt.js';
import type { Response } from 'supertest';
// Тестовые учётные данные (константы, не являются реальными паролями)
const TEST_EMAIL = 'user@example.com';
const TEST_CREDENTIAL = 'Test-Cred-123';
const WRONG_CREDENTIAL = 'Wrong-Cred-123';
/**
* Извлекает значение поля из объекта.
*
* @param obj — объект
* @param key — имя поля
* @returns значение поля (или undefined)
*/
function fieldOf(obj: unknown, key: string): string | undefined {
if (typeof obj !== 'object' || obj === null) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
const record = obj as Record<string, unknown>;
const value = record[key];
return typeof value === 'string' ? value : undefined;
}
/**
* Извлекает токен из тела ответа.
*
* @param body — тело ответа (any из supertest)
* @returns токен (или undefined)
*/
function tokenOf(body: unknown): string | undefined {
return fieldOf(body, 'token');
}
/**
* Извлекает user.email из тела ответа.
*
* @param body — тело ответа (any из supertest)
* @returns email (или undefined)
*/
function userEmailOf(body: unknown): string | undefined {
if (typeof body !== 'object' || body === null) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
const record = body as Record<string, unknown>;
// /me возвращает { id, email } на верхнем уровне, register/login — { user: { id, email } }
if (record.email !== undefined) {
return fieldOf(record, 'email');
}
return fieldOf(record.user, 'email');
}
/**
* Извлекает user.id из тела ответа.
*
* @param body — тело ответа (any из supertest)
* @returns id (или undefined)
*/
function userIdOf(body: unknown): string | undefined {
if (typeof body !== 'object' || body === null) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
const user = (body as Record<string, unknown>).user;
return fieldOf(user, 'id');
}
/**
* Тесты авторизации: регистрация, логин, JWT, protected endpoint.
*/
describe('Auth', () => {
const app = createApp();
describe('POST /api/auth/register', () => {
it('регистрация нового пользователя возвращает 201 и токен', async () => {
const res: Response = await request(app)
.post('/api/auth/register')
.send({ email: TEST_EMAIL, password: TEST_CREDENTIAL });
expect(res.status).toBe(201);
expect(tokenOf(res.body)).toBeDefined();
expect(userEmailOf(res.body)).toBe(TEST_EMAIL);
});
it('повторная регистрация того же email возвращает 409', async () => {
const creds = { email: 'dup@example.com', password: TEST_CREDENTIAL };
const res1 = await request(app).post('/api/auth/register').send(creds);
expect(res1.status).toBe(201);
const res2 = await request(app).post('/api/auth/register').send(creds);
expect(res2.status).toBe(409);
});
it('короткий пароль возвращает 400', async () => {
const shortCred = '123';
const res = await request(app)
.post('/api/auth/register')
.send({ email: 'short@example.com', password: shortCred });
expect(res.status).toBe(400);
});
it('некорректный email возвращает 400', async () => {
const res = await request(app)
.post('/api/auth/register')
.send({ email: 'not-an-email', password: TEST_CREDENTIAL });
expect(res.status).toBe(400);
});
});
describe('POST /api/auth/login', () => {
it('логин существующего пользователя возвращает 200 и токен', async () => {
const creds = { email: 'login@example.com', password: TEST_CREDENTIAL };
await request(app).post('/api/auth/register').send(creds);
const res: Response = await request(app).post('/api/auth/login').send(creds);
expect(res.status).toBe(200);
expect(tokenOf(res.body)).toBeDefined();
expect(userEmailOf(res.body)).toBe('login@example.com');
});
it('логин с неверным паролем возвращает 401', async () => {
const creds = { email: 'badpass@example.com', password: TEST_CREDENTIAL };
await request(app).post('/api/auth/register').send(creds);
const res = await request(app)
.post('/api/auth/login')
.send({ email: 'badpass@example.com', password: WRONG_CREDENTIAL });
expect(res.status).toBe(401);
});
it('логин несуществующего пользователя возвращает 401', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({ email: 'nobody@example.com', password: TEST_CREDENTIAL });
expect(res.status).toBe(401);
});
});
describe('JWT', () => {
it('токен содержит id пользователя в payload', async () => {
const creds = { email: 'jwt@example.com', password: TEST_CREDENTIAL };
const regRes: Response = await request(app).post('/api/auth/register').send(creds);
const token = tokenOf(regRes.body);
expect(token).toBeDefined();
const payload = verifyUserToken(token ?? '');
expect(payload.id).toBeDefined();
expect(payload.sub).toBe(payload.id);
expect(payload.id).toBe(userIdOf(regRes.body));
});
});
describe('GET /api/auth/me', () => {
it('защищённый endpoint без токена возвращает 401', async () => {
const res = await request(app).get('/api/auth/me');
expect(res.status).toBe(401);
});
it('защищённый endpoint с невалидным токеном возвращает 401', async () => {
const res = await request(app)
.get('/api/auth/me')
.set('Authorization', 'Bearer invalid-token');
expect(res.status).toBe(401);
});
it('защищённый endpoint с валидным токеном возвращает данные пользователя', async () => {
const creds = { email: 'me@example.com', password: TEST_CREDENTIAL };
const regRes: Response = await request(app).post('/api/auth/register').send(creds);
const token = tokenOf(regRes.body);
expect(token).toBeDefined();
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- token проверен
const authHeader = `Bearer ${token}`;
const res = await request(app)
.get('/api/auth/me')
.set('Authorization', authHeader);
expect(res.status).toBe(200);
expect(userEmailOf(res.body)).toBe('me@example.com');
});
});
});