Skip to content

Open-source status page, incident response and uptime monitoring

6.5 KB
Raw Blame
import { selectNotificationSchema } from "@openstatus/db/src/schema";
import { COLOR_DECIMALS } from "@openstatus/notification-base";
import {
  afterEach,
  beforeEach,
  describe,
  expect,
  test,
  vi,
  type MockInstance,
} from "vitest";

import {
  buildAlertEmbed,
  buildDegradedEmbed,
  buildRecoveryEmbed,
} from "./embeds";
import {
  sendAlert,
  sendDegraded,
  sendRecovery,
  sendTestDiscordMessage,
} from "./index";

const ok = (): Promise<Response> =>
  Promise.resolve(new Response(null, { status: 200 }));

describe("Discord Notifications", () => {
  let fetchMock: MockInstance;

  beforeEach(() => {
    fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(ok);
  });

  afterEach(() => {
    fetchMock.mockRestore();
  });

  const createMockMonitor = () => ({
    id: "monitor-1",
    name: "API Health Check",
    url: "https://api.example.com/health",
    jobType: "http" as const,
    periodicity: "5m" as const,
    status: "active" as const,
    createdAt: new Date(),
    updatedAt: new Date(),
    region: "iad",
  });

  const createMockNotification = () => ({
    id: 1,
    name: "Discord Notification",
    provider: "discord",
    workspaceId: 1,
    createdAt: new Date(),
    updatedAt: new Date(),
    data: '{"discord":"https://discord.com/api/webhooks/123456789/abcdefgh"}',
  });

  test("Send Alert", async () => {
    const monitor = createMockMonitor();
    const notification = selectNotificationSchema.parse(
      createMockNotification(),
    );

    await sendAlert({
      // @ts-expect-error
      monitor,
      notification,
      statusCode: 500,
      message: "Something went wrong",
      cronTimestamp: Date.now(),
    });

    expect(fetchMock).toHaveBeenCalledTimes(1);
    const callArgs = fetchMock.mock.calls[0];
    expect(callArgs[0]).toBe(
      "https://discord.com/api/webhooks/123456789/abcdefgh",
    );
    expect(callArgs[1].method).toBe("POST");
    expect(callArgs[1].headers["Content-Type"]).toBe("application/json");

    const body = JSON.parse(callArgs[1].body);
    expect(body.embeds).toBeDefined();
    expect(body.embeds[0].title).toContain("is failing");
    expect(body.embeds[0].title).toContain("API Health Check");
    expect(body.embeds[0].color).toBe(COLOR_DECIMALS.red);
    expect(body.username).toBe("OpenStatus Notifications");
    expect(body.avatar_url).toBeDefined();
  });

  test("Send Recovery", async () => {
    const monitor = createMockMonitor();
    const notification = selectNotificationSchema.parse(
      createMockNotification(),
    );

    await sendRecovery({
      // @ts-expect-error
      monitor,
      notification,
      statusCode: 200,
      message: "Service recovered",
      cronTimestamp: Date.now(),
    });

    expect(fetchMock).toHaveBeenCalledTimes(1);
    const callArgs = fetchMock.mock.calls[0];
    const body = JSON.parse(callArgs[1].body);
    expect(body.embeds).toBeDefined();
    expect(body.embeds[0].title).toContain("is recovered");
    expect(body.embeds[0].title).toContain("API Health Check");
    expect(body.embeds[0].color).toBe(COLOR_DECIMALS.green);
  });

  test("Send Degraded", async () => {
    const monitor = createMockMonitor();
    const notification = selectNotificationSchema.parse(
      createMockNotification(),
    );

    await sendDegraded({
      // @ts-expect-error
      monitor,
      notification,
      statusCode: 503,
      message: "Service degraded",
      cronTimestamp: Date.now(),
    });

    expect(fetchMock).toHaveBeenCalledTimes(1);
    const callArgs = fetchMock.mock.calls[0];
    const body = JSON.parse(callArgs[1].body);
    expect(body.embeds).toBeDefined();
    expect(body.embeds[0].title).toContain("is degraded");
    expect(body.embeds[0].title).toContain("API Health Check");
    expect(body.embeds[0].color).toBe(COLOR_DECIMALS.yellow); // Yellow color
  });

  test("Send Test Discord Message", async () => {
    const webhookUrl = "https://discord.com/api/webhooks/123456789/abcdefgh";
    await sendTestDiscordMessage(webhookUrl);

    expect(fetchMock).toHaveBeenCalledTimes(1);
    const callArgs = fetchMock.mock.calls[0];
    expect(callArgs[0]).toBe(webhookUrl);
    const body = JSON.parse(callArgs[1].body);
    expect(body.embeds).toBeDefined();
    expect(body.embeds[0].title).toContain("Test Notification");
  });

  test("Send Test Discord Message with empty webhookUrl", async () => {
    await expect(sendTestDiscordMessage("")).rejects.toThrow();
    expect(fetchMock).toHaveBeenCalledTimes(0);
  });

  test("Handle fetch error gracefully", async () => {
    fetchMock.mockRestore();
    fetchMock = vi
      .spyOn(globalThis, "fetch")
      .mockImplementation(() => Promise.reject(new Error("Network error")));

    const monitor = createMockMonitor();
    const notification = selectNotificationSchema.parse(
      createMockNotification(),
    );
    await expect(
      sendAlert({
        // @ts-expect-error
        monitor,
        notification,
        statusCode: 500,
        message: "Error",
        cronTimestamp: Date.now(),
      }),
    ).rejects.toThrow();
  });
});

describe("Discord title limits", () => {
  for (const [build, suffix] of [
    [buildAlertEmbed, " is failing"],
    [buildRecoveryEmbed, " is recovered"],
    [buildDegradedEmbed, " is degraded"],
  ] as const) {
    test(`${build.name} keeps the status and complete characters within 256 characters`, () => {
      for (const monitorName of [
        "API Health",
        "A".repeat(256 - suffix.length),
        "A".repeat(255),
        "\u{1F680}".repeat(127),
        `A${"\u{1F680}".repeat(127)}`,
      ]) {
        const data = Object.freeze({
          monitorName,
          monitorUrl: "https://example.com/health",
          monitorJobType: "http",
          statusCodeFormatted: "503 Service Unavailable",
          errorMessage: "Connection timeout",
          timestampFormatted: "Sep 9, 2026 at 00:00 UTC",
          regionsDisplay: "iad",
          latencyDisplay: "100ms",
          dashboardUrl: "https://app.openstatus.dev/monitors/1",
        });
        const title = build(data).title;
        expect(title.length).toBeLessThanOrEqual(256);
        expect(title.endsWith(suffix)).toBe(true);
        const name = title.slice(0, -suffix.length);
        expect(name.isWellFormed()).toBe(true);
        expect(name.length).toBeGreaterThan(0);
        expect(monitorName.startsWith(name)).toBe(true);
        if (monitorName.length <= 256 - suffix.length) {
          expect(name).toBe(monitorName);
        }
        expect(data.monitorName).toBe(monitorName);
      }
    });
  }
});