Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/foundation/src/notifications.test.ts
T
2026-07-08 16:15:37 +02:00

177 lines
7.0 KiB
TypeScript

import { describe, expect, test, vi } from "vitest";
import {
assertI18nKey,
bundleNotifications,
isNotificationEnabled,
notify,
type NotificationClient,
type NotificationInput,
} from "./notifications.js";
function createClient() {
return {
notificationDelivery: {
create: vi.fn(async (args: { data: unknown }) => args.data),
upsert: vi.fn(async (args: { create: unknown }) => args.create),
},
} satisfies NotificationClient;
}
describe("assertI18nKey", () => {
test("returns valid dotted/dashed lowercase keys", () => {
expect(assertI18nKey("foundation.errors.not-found")).toBe("foundation.errors.not-found");
expect(assertI18nKey("a")).toBe("a");
});
test("rejects keys that do not match the i18n key grammar", () => {
expect(() => assertI18nKey("Foundation.Bad")).toThrow(/Invalid i18n key/);
expect(() => assertI18nKey("1leading.digit")).toThrow(/Invalid i18n key/);
expect(() => assertI18nKey("trailing.")).toThrow(/Invalid i18n key/);
expect(() => assertI18nKey("")).toThrow(/Invalid i18n key/);
});
});
describe("notify payload sanitization", () => {
test("keeps boolean and null metadata values while dropping empty keys", async () => {
const client = createClient();
await notify(
{
tenantId: "tenant_1",
userId: "user_1",
messageKey: "foundation.notifications.flags",
payloadMetadata: { active: true, dismissed: false, cleared: null, " ": "ignored" },
},
client,
);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
data: expect.objectContaining({ payloadMetadata: { active: true, dismissed: false, cleared: null } }),
});
});
test("drops non-serializable values and yields null metadata when nothing survives", async () => {
const client = createClient();
await notify(
{
tenantId: "tenant_1",
userId: "user_1",
messageKey: "foundation.notifications.empty",
payloadMetadata: { nested: { deep: 1 }, infinite: Number.POSITIVE_INFINITY, broken: Number.NaN },
},
client,
);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ payloadMetadata: null }) });
});
test("truncates over-long string metadata to the configured maximum", async () => {
const client = createClient();
await notify(
{ tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.long", payloadMetadata: { note: "x".repeat(600) } },
client,
);
const call = client.notificationDelivery.create.mock.calls[0][0] as { data: { payloadMetadata: { note: string } } };
expect(call.data.payloadMetadata.note).toHaveLength(500);
});
});
describe("notify status mapping", () => {
test("queues EMAIL deliveries as PENDING with no send timestamp", async () => {
const client = createClient();
await notify({ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", messageKey: "foundation.notifications.invoice" }, client);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
data: expect.objectContaining({ channel: "EMAIL", status: "PENDING", attemptsMade: 0, sentAt: null, lastError: null }),
});
});
test("marks deliveries SKIPPED when a preference disables the channel", async () => {
const client = createClient();
await notify(
{ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", messageKey: "foundation.notifications.invoice" },
client,
[{ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", enabled: false }],
);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
data: expect.objectContaining({ status: "SKIPPED", attemptsMade: 0, lastError: "preference_disabled", sentAt: null }),
});
});
test("persists a null user id for tenant-wide deliveries", async () => {
const client = createClient();
await notify({ tenantId: "tenant_1", messageKey: "foundation.notifications.broadcast" }, client);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ userId: null, channel: "IN_APP", status: "SENT" }) });
// Without a userId the source-key upsert path is never taken.
expect(client.notificationDelivery.upsert).not.toHaveBeenCalled();
});
test("rejects an unscoped tenant before any write", async () => {
const client = createClient();
await expect(notify({ tenantId: " ", userId: "user_1", messageKey: "foundation.notifications.x" }, client)).rejects.toThrow(
"Notification delivery tenant scope is required.",
);
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
});
});
describe("isNotificationEnabled", () => {
test("defaults to enabled when no preference exists for the scope", () => {
expect(isNotificationEnabled({ tenantId: "tenant_1", userId: "user_1", messageKey: "k" }, [])).toBe(true);
});
test("normalizes the category before matching preferences", () => {
const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: " Ops ", messageKey: "k" };
expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", enabled: false }])).toBe(false);
});
test("treats a null userId distinctly from a concrete user", () => {
const input: NotificationInput = { tenantId: "tenant_1", userId: null, channel: "IN_APP", category: "ops", messageKey: "k" };
expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", enabled: false }])).toBe(true);
});
});
describe("bundleNotifications", () => {
test("merges same-scope messages and deduplicates message keys", () => {
const bundles = bundleNotifications([
{ tenantId: "tenant_1", userId: "user_1", messageKey: "a" },
{ tenantId: "tenant_1", userId: "user_1", messageKey: "a" },
{ tenantId: "tenant_1", userId: "user_1", messageKey: "b", payloadMetadata: { count: 2 } },
]);
expect(bundles).toEqual([
{
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKeys: ["a", "b"],
payloadMetadata: { count: 2 },
},
]);
});
test("bundles tenant-wide messages under a null user id", () => {
const bundles = bundleNotifications([
{ tenantId: "tenant_1", messageKey: "a" },
{ tenantId: "tenant_1", messageKey: "b" },
]);
expect(bundles).toHaveLength(1);
expect(bundles[0]).toMatchObject({ userId: null, messageKeys: ["a", "b"] });
});
test("separates bundles across distinct channel/category scopes", () => {
const bundles = bundleNotifications([
{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", messageKey: "a" },
{ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "ops", messageKey: "b" },
]);
expect(bundles).toHaveLength(2);
expect(bundles.map((bundle) => bundle.channel)).toEqual(["IN_APP", "EMAIL"]);
});
});