Files
TREK/server/tests/integration/notifications.test.ts
T
Maurice 741bb651e5 test(db): run the OIDC, passkey, profile, notifications and ORM request context seam suites on the real database module
They reset through resetDatabase (the seam suite needs no reset) and seed
through the ORM factories instead of the SQLite snapshot mock, so they run
in the Postgres lane as well.
2026-11-17 17:00:56 +01:00

564 lines
24 KiB
TypeScript

/**
* Notifications integration tests.
* Covers NOTIF-001 to NOTIF-014.
*
* External SMTP / webhook calls are not made — tests focus on preferences,
* in-app notification CRUD, and authentication.
*/
import { buildApp } from '../../src/bootstrap';
import { NotificationChannelPreferences } from '../../src/db/entities/NotificationChannelPreferences.entity';
import { Notifications } from '../../src/db/entities/Notifications.entity';
import { authCookie } from '../helpers/auth';
import type { FactoryOrm } from '../helpers/factories/context';
import { disableNotificationPref } from '../helpers/factories/notifications';
import { makeNotification } from '../helpers/factories/notifications';
import { findRow, updateRows } from '../helpers/factories/rows';
import { setUserSetting } from '../helpers/factories/settings';
import { makeAdmin, makeUser } from '../helpers/factories/users';
import { resetDatabase } from '../helpers/reset-database';
import { resetRateLimits } from '../helpers/test-db';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import type { Application } from 'express';
import request from 'supertest';
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// The two test-send endpoints must not reach a real SMTP server or URL. Since
// the fold they are provider methods, so they are stubbed on the prototype
// rather than by module path — everything else in the domain stays real.
vi.mock('../../src/nest/notifications/mailer/mailer.service', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/nest/notifications/mailer/mailer.service')>();
actual.MailerService.prototype.testSmtp = vi.fn().mockResolvedValue({ success: true });
return actual;
});
vi.mock('../../src/nest/notifications/transports/webhook.service', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/nest/notifications/transports/webhook.service')>();
actual.WebhookService.prototype.testWebhook = vi.fn().mockResolvedValue({ success: true });
return actual;
});
let nestApp: INestApplication;
let app: Application;
/** The app's own ORM, which the factories seed and read through. */
const orm = (): FactoryOrm => nestApp.get(MikroORM);
beforeAll(async () => {
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
});
beforeEach(async () => {
await resetDatabase(orm());
await resetRateLimits(nestApp);
});
afterAll(async () => {
await nestApp.close();
});
describe('Notification preferences', () => {
it('NOTIF-001 — GET /api/notifications/preferences returns defaults', async () => {
const { user } = await makeUser(orm());
const res = await request(app).get('/api/notifications/preferences').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('preferences');
});
it('NOTIF-001 — PUT /api/notifications/preferences updates settings', async () => {
const { user } = await makeUser(orm());
// The DTO ratchet enforces the matrix shape the client actually sends
// ({ event: { channel: enabled } }); the pre-matrix flat notify_* body
// this case used to send is rejected by the pipe now.
const res = await request(app)
.put('/api/notifications/preferences')
.set('Cookie', authCookie(user.id))
.send({ trip_invite: { email: true }, booking_change: { email: false } });
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('preferences');
});
it('NOTIF — GET preferences without auth returns 401', async () => {
const res = await request(app).get('/api/notifications/preferences');
expect(res.status).toBe(401);
});
});
describe('In-app notifications', () => {
it('NOTIF-008 — GET /api/notifications/in-app returns notifications array', async () => {
const { user } = await makeUser(orm());
const res = await request(app).get('/api/notifications/in-app').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(Array.isArray(res.body.notifications)).toBe(true);
});
it('NOTIF-008 — GET /api/notifications/in-app/unread-count returns count', async () => {
const { user } = await makeUser(orm());
const res = await request(app).get('/api/notifications/in-app/unread-count').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('count');
expect(typeof res.body.count).toBe('number');
});
it('NOTIF-009 — PUT /api/notifications/in-app/read-all marks all read', async () => {
const { user } = await makeUser(orm());
const res = await request(app).put('/api/notifications/in-app/read-all').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
});
it('NOTIF-010 — DELETE /api/notifications/in-app/all deletes all notifications', async () => {
const { user } = await makeUser(orm());
const res = await request(app).delete('/api/notifications/in-app/all').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
});
it('NOTIF-011 — PUT /api/notifications/in-app/:id/read on non-existent returns 404', async () => {
const { user } = await makeUser(orm());
const res = await request(app).put('/api/notifications/in-app/99999/read').set('Cookie', authCookie(user.id));
expect(res.status).toBe(404);
});
it('NOTIF-012 — DELETE /api/notifications/in-app/:id on non-existent returns 404', async () => {
const { user } = await makeUser(orm());
const res = await request(app).delete('/api/notifications/in-app/99999').set('Cookie', authCookie(user.id));
expect(res.status).toBe(404);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// New preferences matrix API (NROUTE series)
// ─────────────────────────────────────────────────────────────────────────────
describe('GET /api/notifications/preferences — matrix format', () => {
it('NROUTE-002 — returns preferences, channels, event_types, implemented_combos', async () => {
const { user } = await makeUser(orm());
const res = await request(app).get('/api/notifications/preferences').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('preferences');
expect(res.body).toHaveProperty('channels');
expect(res.body).toHaveProperty('event_types');
expect(res.body).toHaveProperty('implemented_combos');
const inapp = res.body.channels.find((c: { id: string }) => c.id === 'inapp');
expect(inapp.active).toBe(true);
// The built-in external channels are always described, active or not.
expect(res.body.channels.map((c: { id: string }) => c.id)).toEqual(
expect.arrayContaining(['inapp', 'email', 'webhook', 'ntfy']),
);
});
it('NROUTE-003 — regular user does not see version_available in event_types', async () => {
const { user } = await makeUser(orm());
const res = await request(app).get('/api/notifications/preferences').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.event_types).not.toContain('version_available');
});
it('NROUTE-004 — user preferences endpoint excludes version_available even for admins', async () => {
const { user } = await makeAdmin(orm());
const res = await request(app).get('/api/notifications/preferences').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.event_types).not.toContain('version_available');
});
it('NROUTE-004b — admin notification preferences endpoint returns version_available', async () => {
const { user } = await makeAdmin(orm());
const res = await request(app).get('/api/admin/notification-preferences').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.event_types).toContain('version_available');
});
it('NROUTE-005 — all preferences default to true for new user with no stored prefs', async () => {
const { user } = await makeUser(orm());
const res = await request(app).get('/api/notifications/preferences').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
const { preferences } = res.body;
for (const [, channels] of Object.entries(preferences)) {
for (const [, enabled] of Object.entries(channels as Record<string, boolean>)) {
expect(enabled).toBe(true);
}
}
});
});
describe('PUT /api/notifications/preferences — matrix format', () => {
it('NROUTE-007 — disabling a preference persists and is reflected in subsequent GET', async () => {
const { user } = await makeUser(orm());
const putRes = await request(app)
.put('/api/notifications/preferences')
.set('Cookie', authCookie(user.id))
.send({ trip_invite: { email: false } });
expect(putRes.status).toBe(200);
expect(putRes.body.preferences['trip_invite']['email']).toBe(false);
const getRes = await request(app).get('/api/notifications/preferences').set('Cookie', authCookie(user.id));
expect(getRes.body.preferences['trip_invite']['email']).toBe(false);
});
it('NROUTE-008 — re-enabling a preference restores default state', async () => {
const { user } = await makeUser(orm());
await disableNotificationPref(orm(), user.id, 'trip_invite', 'email');
const res = await request(app)
.put('/api/notifications/preferences')
.set('Cookie', authCookie(user.id))
.send({ trip_invite: { email: true } });
expect(res.status).toBe(200);
expect(res.body.preferences['trip_invite']['email']).toBe(true);
const row = await findRow(orm(), NotificationChannelPreferences, {
user: user.id,
event_type: 'trip_invite',
channel: 'email',
});
expect(row).toBeNull();
});
it('NROUTE-009 — partial update does not affect other preferences', async () => {
const { user } = await makeUser(orm());
await disableNotificationPref(orm(), user.id, 'booking_change', 'email');
await request(app)
.put('/api/notifications/preferences')
.set('Cookie', authCookie(user.id))
.send({ trip_invite: { email: false } });
const getRes = await request(app).get('/api/notifications/preferences').set('Cookie', authCookie(user.id));
expect(getRes.body.preferences['booking_change']['email']).toBe(false);
expect(getRes.body.preferences['trip_invite']['email']).toBe(false);
expect(getRes.body.preferences['trip_reminder']['email']).toBe(true);
});
});
describe('implemented_combos — in-app channel coverage', () => {
it('NROUTE-010 — implemented_combos includes inapp for all event types', async () => {
const { user } = await makeUser(orm());
const res = await request(app).get('/api/notifications/preferences').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
const { implemented_combos } = res.body as { implemented_combos: Record<string, string[]> };
const eventTypes = [
'trip_invite',
'booking_change',
'trip_reminder',
'vacay_invite',
'photos_shared',
'collab_message',
'packing_tagged',
];
for (const event of eventTypes) {
expect(implemented_combos[event], `${event} should support inapp`).toContain('inapp');
expect(implemented_combos[event], `${event} should support email`).toContain('email');
expect(implemented_combos[event], `${event} should support webhook`).toContain('webhook');
}
});
});
describe('Notification test endpoints', () => {
it('NOTIF-005 — POST /api/notifications/test-smtp requires admin', async () => {
const { user } = await makeUser(orm());
// Send the empty JSON body the client sends ({ email: undefined } →
// {}): a completely body-less POST has no content-type, so the DTO pipe
// rejects it before the admin gate since the ratchet.
const res = await request(app).post('/api/notifications/test-smtp').set('Cookie', authCookie(user.id)).send({});
// Non-admin gets 403
expect(res.status).toBe(403);
});
it('NOTIF-006 — POST /api/notifications/test-webhook returns 400 when url is missing', async () => {
const { user } = await makeUser(orm());
const res = await request(app).post('/api/notifications/test-webhook').set('Cookie', authCookie(user.id)).send({});
expect(res.status).toBe(400);
});
it('NOTIF-006b — POST /api/notifications/test-webhook returns 400 for invalid URL', async () => {
const { user } = await makeUser(orm());
const res = await request(app)
.post('/api/notifications/test-webhook')
.set('Cookie', authCookie(user.id))
.send({ url: 'not-a-url' });
expect(res.status).toBe(400);
});
it('NOTIF-005b — admin can call test-smtp and gets a result', async () => {
const { user } = await makeAdmin(orm());
const res = await request(app)
.post('/api/notifications/test-smtp')
.set('Cookie', authCookie(user.id))
.send({ email: 'test@example.com' });
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('success');
});
it('NOTIF-006c — POST /api/notifications/test-webhook with valid URL calls testWebhook', async () => {
const { user } = await makeUser(orm());
const res = await request(app)
.post('/api/notifications/test-webhook')
.set('Cookie', authCookie(user.id))
.send({ url: 'https://webhook.site/test-endpoint' });
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('success');
});
it('NOTIF-007 — POST /api/notifications/test-ntfy returns 400 when no topic configured', async () => {
const { user } = await makeUser(orm());
const res = await request(app).post('/api/notifications/test-ntfy').set('Cookie', authCookie(user.id)).send({});
expect(res.status).toBe(400);
expect(res.body).toHaveProperty('error');
});
it('NOTIF-008 — POST /api/notifications/test-ntfy with explicit topic returns 200', async () => {
const { user } = await makeUser(orm());
const res = await request(app)
.post('/api/notifications/test-ntfy')
.set('Cookie', authCookie(user.id))
.send({ topic: 'trek-integration-test-topic' });
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('success');
});
it('NOTIF-009 — POST /api/notifications/test-ntfy falls back to user saved topic', async () => {
const { user } = await makeUser(orm());
await setUserSetting(orm(), user.id, 'ntfy_topic', 'saved-user-topic');
const res = await request(app).post('/api/notifications/test-ntfy').set('Cookie', authCookie(user.id)).send({});
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('success');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Helper: insert a boolean notification directly into the DB
// ─────────────────────────────────────────────────────────────────────────────
async function insertBooleanNotification(recipientId: number): Promise<number> {
const row = await makeNotification(orm(), recipientId, {
type: 'boolean',
target: recipientId,
sender: null,
title_key: 'notif.test.title',
title_params: '{}',
text_key: 'notif.test.text',
text_params: '{}',
positive_text_key: 'notif.action.accept',
negative_text_key: 'notif.action.decline',
positive_callback: '{"action":"test_approve","payload":{}}',
negative_callback: '{"action":"test_deny","payload":{}}',
});
return row.id;
}
async function insertSimpleNotification(recipientId: number): Promise<number> {
const row = await makeNotification(orm(), recipientId, {
type: 'simple',
target: recipientId,
sender: null,
title_key: 'notif.test.title',
title_params: '{}',
text_key: 'notif.test.text',
text_params: '{}',
});
return row.id;
}
// ─────────────────────────────────────────────────────────────────────────────
// POST /in-app/:id/respond
// ─────────────────────────────────────────────────────────────────────────────
describe('POST /api/notifications/in-app/:id/respond', () => {
it('NROUTE-011 — valid positive response returns success and updated notification', async () => {
const { user } = await makeUser(orm());
const id = await insertBooleanNotification(user.id);
const res = await request(app)
.post(`/api/notifications/in-app/${id}/respond`)
.set('Cookie', authCookie(user.id))
.send({ response: 'positive' });
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.notification).toBeDefined();
expect(res.body.notification.response).toBe('positive');
});
it('NROUTE-012 — invalid response value returns 400', async () => {
const { user } = await makeUser(orm());
const id = await insertBooleanNotification(user.id);
const res = await request(app)
.post(`/api/notifications/in-app/${id}/respond`)
.set('Cookie', authCookie(user.id))
.send({ response: 'maybe' });
expect(res.status).toBe(400);
});
it('NROUTE-013 — response on non-existent notification returns 400', async () => {
const { user } = await makeUser(orm());
const res = await request(app)
.post('/api/notifications/in-app/99999/respond')
.set('Cookie', authCookie(user.id))
.send({ response: 'positive' });
expect(res.status).toBe(400);
});
it('NROUTE-014 — double response returns 400', async () => {
const { user } = await makeUser(orm());
const id = await insertBooleanNotification(user.id);
await request(app)
.post(`/api/notifications/in-app/${id}/respond`)
.set('Cookie', authCookie(user.id))
.send({ response: 'positive' });
const res = await request(app)
.post(`/api/notifications/in-app/${id}/respond`)
.set('Cookie', authCookie(user.id))
.send({ response: 'negative' });
expect(res.status).toBe(400);
expect(res.body.error).toMatch(/already responded/i);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// PUT /api/admin/notification-preferences
// ─────────────────────────────────────────────────────────────────────────────
describe('PUT /api/admin/notification-preferences', () => {
it('NROUTE-015 — admin can disable email for version_available, persists in GET', async () => {
const { user } = await makeAdmin(orm());
const putRes = await request(app)
.put('/api/admin/notification-preferences')
.set('Cookie', authCookie(user.id))
.send({ version_available: { email: false } });
expect(putRes.status).toBe(200);
expect(putRes.body.preferences['version_available']['email']).toBe(false);
const getRes = await request(app).get('/api/admin/notification-preferences').set('Cookie', authCookie(user.id));
expect(getRes.status).toBe(200);
expect(getRes.body.preferences['version_available']['email']).toBe(false);
});
it('NROUTE-016 — non-admin is rejected with 403', async () => {
const { user } = await makeUser(orm());
const res = await request(app)
.put('/api/admin/notification-preferences')
.set('Cookie', authCookie(user.id))
.send({ version_available: { email: false } });
expect(res.status).toBe(403);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// In-app CRUD with actual notification data
// ─────────────────────────────────────────────────────────────────────────────
describe('In-app notifications — CRUD with data', () => {
it('NROUTE-017 — GET /in-app returns created notifications', async () => {
const { user } = await makeUser(orm());
await insertSimpleNotification(user.id);
await insertSimpleNotification(user.id);
const res = await request(app).get('/api/notifications/in-app').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.notifications.length).toBe(2);
expect(res.body.total).toBe(2);
expect(res.body.unread_count).toBe(2);
});
it('NROUTE-018 — unread count reflects actual unread notifications', async () => {
const { user } = await makeUser(orm());
await insertSimpleNotification(user.id);
await insertSimpleNotification(user.id);
const res = await request(app).get('/api/notifications/in-app/unread-count').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.count).toBe(2);
});
it('NROUTE-019 — mark-read on existing notification succeeds and decrements unread count', async () => {
const { user } = await makeUser(orm());
const id = await insertSimpleNotification(user.id);
const markRes = await request(app).put(`/api/notifications/in-app/${id}/read`).set('Cookie', authCookie(user.id));
expect(markRes.status).toBe(200);
expect(markRes.body.success).toBe(true);
const countRes = await request(app)
.get('/api/notifications/in-app/unread-count')
.set('Cookie', authCookie(user.id));
expect(countRes.body.count).toBe(0);
});
it('NROUTE-020 — mark-unread on a read notification succeeds', async () => {
const { user } = await makeUser(orm());
const id = await insertSimpleNotification(user.id);
// Mark read first
await updateRows(orm(), Notifications, { id }, { is_read: 1 });
const res = await request(app).put(`/api/notifications/in-app/${id}/unread`).set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
const row = await findRow(orm(), Notifications, { id });
expect(row?.is_read).toBe(0);
});
it('NROUTE-021 — DELETE on existing notification removes it', async () => {
const { user } = await makeUser(orm());
const id = await insertSimpleNotification(user.id);
const res = await request(app).delete(`/api/notifications/in-app/${id}`).set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(await findRow(orm(), Notifications, { id })).toBeNull();
});
it('NROUTE-022 — unread_only=true filter returns only unread notifications', async () => {
const { user } = await makeUser(orm());
const id1 = await insertSimpleNotification(user.id);
await insertSimpleNotification(user.id);
// Mark first one read
await updateRows(orm(), Notifications, { id: id1 }, { is_read: 1 });
const res = await request(app).get('/api/notifications/in-app?unread_only=true').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.notifications.length).toBe(1);
expect(res.body.notifications[0].is_read).toBe(0);
});
});