145 lines
5.8 KiB
TypeScript
145 lines
5.8 KiB
TypeScript
import request from 'supertest';
|
|
import { describe, expect, it, beforeAll, afterAll } from 'vitest';
|
|
|
|
import { createApp } from '../src/app.js';
|
|
import News from '../src/models/news.model.js';
|
|
import { User, hashPassword } from '../src/models/user.model.js';
|
|
import { startPublicationScheduler, stopPublicationScheduler } from '../src/services/publicationScheduler.service.js';
|
|
import { signUserToken } from '../src/utils/jwt.js';
|
|
|
|
const app = createApp();
|
|
const TEST_EMAIL = 'publish-test@example.com';
|
|
|
|
let authToken = '';
|
|
|
|
beforeAll(async () => {
|
|
const user = await User.create({
|
|
email: TEST_EMAIL,
|
|
passwordHash: await hashPassword('Test-Pass-123'),
|
|
});
|
|
authToken = signUserToken(user.id);
|
|
});
|
|
|
|
function authed(req: request.Test): request.Test {
|
|
return req.set('Authorization', `Bearer ${authToken}`);
|
|
}
|
|
|
|
/** Создаёт тестовую новость и возвращает её id. */
|
|
async function createTestNews(title: string): Promise<string> {
|
|
const res = await authed(request(app).post('/api/news').send({ title, content: 'Тест' }));
|
|
return res.body.news.id;
|
|
}
|
|
|
|
describe('Публикация новостей', () => {
|
|
describe('POST /api/news/:id/publish', () => {
|
|
it('публикует draft-новость', async () => {
|
|
const id = await createTestNews('К публикации');
|
|
const res = await authed(request(app).post(`/api/news/${id}/publish`));
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.news.status).toBe('published');
|
|
expect(res.body.news.publishedAt).not.toBeNull();
|
|
});
|
|
|
|
it('повторная публикация возвращает 400', async () => {
|
|
const id = await createTestNews('Уже опубликована');
|
|
await authed(request(app).post(`/api/news/${id}/publish`));
|
|
const res = await authed(request(app).post(`/api/news/${id}/publish`));
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.code).toBe('ALREADY_PUBLISHED');
|
|
});
|
|
|
|
it('несуществующий id возвращает 404', async () => {
|
|
const res = await authed(request(app).post('/api/news/000000000000000000000000/publish'));
|
|
expect(res.status).toBe(404);
|
|
});
|
|
|
|
it('чужая новость — 404', async () => {
|
|
const id = await createTestNews('Своя');
|
|
const user2 = await User.create({
|
|
email: 'publish-other@example.com',
|
|
passwordHash: await hashPassword('Other-Pass-123'),
|
|
});
|
|
const token2 = signUserToken(user2.id);
|
|
|
|
const res = await request(app)
|
|
.post(`/api/news/${id}/publish`)
|
|
.set('Authorization', `Bearer ${token2}`);
|
|
expect(res.status).toBe(404);
|
|
});
|
|
});
|
|
|
|
describe('POST /api/news/:id/schedule', () => {
|
|
it('устанавливает отложенную публикацию', async () => {
|
|
const id = await createTestNews('Отложенная');
|
|
const futureDate = new Date(Date.now() + 3600_000).toISOString();
|
|
|
|
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: futureDate }));
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.news.status).toBe('scheduled');
|
|
expect(res.body.news.scheduledAt).toBe(futureDate);
|
|
});
|
|
|
|
it('дата в прошлом возвращает 400', async () => {
|
|
const id = await createTestNews('Прошлая дата');
|
|
const pastDate = new Date(Date.now() - 3600_000).toISOString();
|
|
|
|
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: pastDate }));
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it('невалидная дата возвращает 400', async () => {
|
|
const id = await createTestNews('Невалидная дата');
|
|
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: 'not-a-date' }));
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it('отсутствие scheduledAt возвращает 400', async () => {
|
|
const id = await createTestNews('Без даты');
|
|
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({}));
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it('уже опубликованная — 400', async () => {
|
|
const id = await createTestNews('Публикация и schedule');
|
|
await authed(request(app).post(`/api/news/${id}/publish`));
|
|
const futureDate = new Date(Date.now() + 3600_000).toISOString();
|
|
|
|
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: futureDate }));
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.code).toBe('ALREADY_PUBLISHED');
|
|
});
|
|
});
|
|
|
|
describe('Publication Scheduler', () => {
|
|
afterAll(() => {
|
|
stopPublicationScheduler();
|
|
});
|
|
|
|
it('автоматически публикует scheduled новости с прошедшим scheduledAt', async () => {
|
|
// Создаём новость и вручную ставим scheduledAt в прошлое
|
|
const id = await createTestNews('Авто-публикация');
|
|
const pastDate = new Date(Date.now() - 60_000);
|
|
await News.updateOne({ _id: id }, { $set: { status: 'scheduled', scheduledAt: pastDate } });
|
|
|
|
// Запускаем scheduler с коротким интервалом
|
|
startPublicationScheduler(500);
|
|
|
|
// Ждём до 3 секунд пока scheduler опубликует
|
|
const deadline = Date.now() + 3000;
|
|
let published = false;
|
|
while (Date.now() < deadline) {
|
|
const news = await News.findById(id);
|
|
if (news?.status === 'published') {
|
|
published = true;
|
|
break;
|
|
}
|
|
|
|
await new Promise<void>((r) => { setTimeout(r, 100); });
|
|
}
|
|
|
|
stopPublicationScheduler();
|
|
expect(published).toBe(true);
|
|
});
|
|
});
|
|
});
|