Skip to content

Open-source status page, incident response and uptime monitoring

8.3 KB
Raw Blame
import "../test-preload.ts";
import { EmailClient } from "@openstatus/emails";
import {
  afterEach,
  beforeEach,
  describe,
  expect,
  test,
  vi,
  type MockInstance,
} from "vitest";

import type { PageUpdate, Subscription } from "../types";
import {
  sendEmailNotifications,
  sendEmailVerification,
  validateEmailConfig,
} from "./email";

// RESEND_API_KEY is set in test-preload.ts (see bunfig.toml) so @openstatus/emails
// loads successfully and EmailClient prototype methods can be spied on.

let sendPageSubscriptionMock: MockInstance;
let sendPageUpdateMock: MockInstance;

function makeSub(overrides: Partial<Subscription> = {}): Subscription {
  return {
    id: 1,
    pageId: 1,
    pageName: "Test Page",
    pageSlug: "test",
    channelType: "email",
    email: "[email protected]",
    token: "token-123",
    componentIds: [],
    ...overrides,
  };
}

function makeUpdate(overrides: Partial<PageUpdate> = {}): PageUpdate {
  return {
    id: 1,
    pageId: 1,
    title: "Test Incident",
    status: "investigating",
    message: "We are investigating.",
    pageComponentIds: [],
    pageComponents: [],
    date: new Date().toISOString(),
    ...overrides,
  };
}

beforeEach(() => {
  sendPageSubscriptionMock = vi
    .spyOn(EmailClient.prototype, "sendPageSubscription")
    .mockImplementation(() => Promise.resolve(undefined));
  sendPageUpdateMock = vi
    .spyOn(EmailClient.prototype, "sendPageUpdate")
    .mockImplementation(() => Promise.resolve(undefined));
});

afterEach(() => {
  sendPageSubscriptionMock.mockRestore();
  sendPageUpdateMock.mockRestore();
});

// ─── validateEmailConfig ──────────────────────────────────────────────────────

describe("validateEmailConfig", () => {
  test("returns valid for a valid email address", async () => {
    const result = await validateEmailConfig("[email protected]");
    expect(result.valid).toBe(true);
  });

  test("returns invalid for a plain string without @", async () => {
    const result = await validateEmailConfig("not-an-email");
    expect(result.valid).toBe(false);
    expect(result.error).toBeDefined();
  });

  test("returns invalid for non-string input", async () => {
    const result = await validateEmailConfig(42);
    expect(result.valid).toBe(false);
  });

  test("returns invalid for null", async () => {
    const result = await validateEmailConfig(null);
    expect(result.valid).toBe(false);
  });
});

// ─── sendEmailVerification ────────────────────────────────────────────────────

describe("sendEmailVerification", () => {
  test("throws when subscription has no email", async () => {
    const sub = makeSub({ email: undefined });
    await expect(
      sendEmailVerification(sub, "https://example.com/verify/token"),
    ).rejects.toThrow("Email is required");
  });

  test("calls sendPageSubscription with the correct arguments", async () => {
    const sub = makeSub({ email: "[email protected]", pageName: "My Page" });
    await sendEmailVerification(sub, "https://example.com/verify/abc");

    expect(sendPageSubscriptionMock).toHaveBeenCalledTimes(1);
    const [args] = sendPageSubscriptionMock.mock.calls[0];
    expect(args.to).toBe("[email protected]");
    expect(args.link).toBe("https://example.com/verify/abc");
    expect(args.page).toBe("My Page");
  });
});

// ─── sendEmailNotifications ───────────────────────────────────────────────────

describe("sendEmailNotifications", () => {
  test("does nothing for an empty subscriptions array", async () => {
    await sendEmailNotifications([], makeUpdate());
    expect(sendPageUpdateMock).toHaveBeenCalledTimes(0);
  });

  test("filters out subscriptions without an email address", async () => {
    const sub = makeSub({ email: undefined });
    await sendEmailNotifications([sub], makeUpdate());
    expect(sendPageUpdateMock).toHaveBeenCalledTimes(0);
  });

  test("calls sendPageUpdate once with all valid subscribers", async () => {
    const sub1 = makeSub({ email: "[email protected]", token: "token-a" });
    const sub2 = makeSub({ email: "[email protected]", token: "token-b" });
    const update = makeUpdate({ title: "Outage", status: "resolved" });

    await sendEmailNotifications([sub1, sub2], update);

    expect(sendPageUpdateMock).toHaveBeenCalledTimes(1);
    const [args] = sendPageUpdateMock.mock.calls[0];
    expect(args.subscribers).toHaveLength(2);
    expect(args.subscribers[0].email).toBe("[email protected]");
    expect(args.subscribers[1].email).toBe("[email protected]");
    expect(args.reportTitle).toBe("Outage");
    expect(args.status).toBe("resolved");
  });

  test("passes page components to sendPageUpdate", async () => {
    const sub = makeSub({ email: "[email protected]" });
    const update = makeUpdate({ pageComponents: ["API", "Database"] });

    await sendEmailNotifications([sub], update);

    const [args] = sendPageUpdateMock.mock.calls[0];
    expect(args.pageComponents).toEqual(["API", "Database"]);
  });

  test("derives the idempotency key from the status-report update id", async () => {
    const sub = makeSub();
    await sendEmailNotifications([sub], makeUpdate({ updateId: 77 }));

    const [args] = sendPageUpdateMock.mock.calls[0];
    expect(args.idempotencyKey).toMatch(/^status-report-update:77:[0-9a-z]+$/);
  });

  test("falls back to a page-update key when there is no update id", async () => {
    const sub = makeSub();
    await sendEmailNotifications(
      [sub],
      makeUpdate({ id: 17, updateId: undefined, status: "maintenance" }),
    );

    const [args] = sendPageUpdateMock.mock.calls[0];
    expect(args.idempotencyKey).toMatch(
      /^page-update:17:maintenance:[0-9a-z]+$/,
    );
  });

  test("keeps the same key for an identical re-dispatch", async () => {
    const update = makeUpdate({ updateId: 77, date: "2026-07-16T11:00:00Z" });
    await sendEmailNotifications([makeSub()], update);
    await sendEmailNotifications([makeSub()], update);

    const keys = sendPageUpdateMock.mock.calls.map((c) => c[0].idempotencyKey);
    expect(keys[0]).toBe(keys[1]);
  });

  test("changes the key when the subscriber list changes", async () => {
    const update = makeUpdate({ updateId: 77, date: "2026-07-16T11:00:00Z" });
    await sendEmailNotifications([makeSub()], update);
    await sendEmailNotifications(
      [makeSub(), makeSub({ id: 2, email: "[email protected]", token: "token-b" })],
      update,
    );

    const keys = sendPageUpdateMock.mock.calls.map((c) => c[0].idempotencyKey);
    expect(keys[0]).not.toBe(keys[1]);
  });

  test("passes the maintenance window alongside the update date", async () => {
    await sendEmailNotifications(
      [makeSub()],
      makeUpdate({
        updateId: 77,
        status: "maintenance",
        date: "2026-07-16T11:00:00Z",
        startsAt: "2026-07-20T10:00:00Z",
        endsAt: "2026-07-20T11:00:00Z",
      }),
    );

    const [args] = sendPageUpdateMock.mock.calls[0];
    expect(args.date).toBe("2026-07-16T11:00:00Z");
    expect(args.startsAt).toBe("2026-07-20T10:00:00Z");
    expect(args.endsAt).toBe("2026-07-20T11:00:00Z");
  });

  test("changes the key when the maintenance window changes", async () => {
    const base = {
      updateId: 77,
      status: "maintenance" as const,
      date: "2026-07-16T11:00:00Z",
      startsAt: "2026-07-20T10:00:00Z",
    };
    await sendEmailNotifications(
      [makeSub()],
      makeUpdate({ ...base, endsAt: "2026-07-20T11:00:00Z" }),
    );
    await sendEmailNotifications(
      [makeSub()],
      makeUpdate({ ...base, endsAt: "2026-07-20T12:00:00Z" }),
    );

    const keys = sendPageUpdateMock.mock.calls.map((c) => c[0].idempotencyKey);
    expect(keys[0]).not.toBe(keys[1]);
  });

  test("changes the key when the update content changes", async () => {
    const date = "2026-07-16T11:00:00Z";
    await sendEmailNotifications(
      [makeSub()],
      makeUpdate({ updateId: 77, date, message: "We are investigating." }),
    );
    await sendEmailNotifications(
      [makeSub()],
      makeUpdate({ updateId: 77, date, message: "Root cause identified." }),
    );

    const keys = sendPageUpdateMock.mock.calls.map((c) => c[0].idempotencyKey);
    expect(keys[0]).not.toBe(keys[1]);
  });
});