add additional tests
This commit is contained in:
1 parent
ef4ca52285
commit
db64ad1de4
9 files changed
+572
-2
No files matched your search
@@ -21,7 +21,15 @@ const config = {
|
|||||||
collectCoverageFrom: ["src/**/*.{ts,js}", "!src/**/*.d.ts"],
|
collectCoverageFrom: ["src/**/*.{ts,js}", "!src/**/*.d.ts"],
|
||||||
coverageDirectory: "coverage",
|
coverageDirectory: "coverage",
|
||||||
coverageReporters: ["text", "lcov"],
|
coverageReporters: ["text", "lcov"],
|
||||||
coveragePathIgnorePatterns: ["/node_modules/", "<rootDir>/src/index.ts"]
|
coveragePathIgnorePatterns: ["/node_modules/", "<rootDir>/src/index.ts"],
|
||||||
|
coverageThreshold: {
|
||||||
|
global: {
|
||||||
|
branches: 80,
|
||||||
|
functions: 90,
|
||||||
|
lines: 90,
|
||||||
|
statements: 90,
|
||||||
|
},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default config;
|
export default config;
|
||||||
@@ -184,7 +184,7 @@ class NotificationService implements INotificationService {
|
|||||||
const result: any[] = [];
|
const result: any[] = [];
|
||||||
await this.testNotification(notificationChannel, result);
|
await this.testNotification(notificationChannel, result);
|
||||||
if (result.length > 0) {
|
if (result.length > 0) {
|
||||||
return result.find((r) => r._id === notificationChannel._id)?.sent;
|
return Boolean(result[0]?.sent);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { addUserContext, invalidateCachesForUser } from "@/middleware/AddUserContext.js";
|
||||||
|
import * as Models from "@/db/models/index.js";
|
||||||
|
import ApiError from "@/utils/ApiError.js";
|
||||||
|
|
||||||
|
const mockReq = (user, headers = {}) => ({ user, headers });
|
||||||
|
const mockRes = () => ({ });
|
||||||
|
const mockNext = () => jest.fn();
|
||||||
|
|
||||||
|
describe("addUserContext", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.spyOn(Models.TeamMembership, "find").mockReturnValue({ select: () => ({ lean: () => [] }) });
|
||||||
|
jest.spyOn(Models.TeamMembership, "findOne").mockReturnValue({ populate: () => ({ select: () => ({ lean: () => ({ roleId: { name: "team-role" } }) }) }) });
|
||||||
|
jest.spyOn(Models.OrgMembership, "findOne").mockReturnValue({ populate: () => ({ select: () => ({ lean: () => ({ roleId: { name: "org-role" } }) }) }) });
|
||||||
|
});
|
||||||
|
afterEach(() => jest.restoreAllMocks());
|
||||||
|
|
||||||
|
it("throws when user missing", async () => {
|
||||||
|
const req = mockReq(undefined, {});
|
||||||
|
const res = mockRes();
|
||||||
|
const next = mockNext();
|
||||||
|
await addUserContext(req, res, next);
|
||||||
|
expect(next).toHaveBeenCalled();
|
||||||
|
const err = next.mock.calls[0][0];
|
||||||
|
expect(err).toBeInstanceOf(ApiError);
|
||||||
|
expect(err.status).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws when user not in selected team", async () => {
|
||||||
|
jest.spyOn(Models.TeamMembership, "find").mockReturnValue({ select: () => ({ lean: () => [{ teamId: "t-2" }] }) });
|
||||||
|
const req = mockReq({ sub: "u1", orgId: "o1" }, { "x-team-id": "t-1" });
|
||||||
|
const res = mockRes();
|
||||||
|
const next = mockNext();
|
||||||
|
await addUserContext(req, res, next);
|
||||||
|
const err = next.mock.calls[0][0];
|
||||||
|
expect(err).toBeInstanceOf(ApiError);
|
||||||
|
expect(err.status).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("populates roles and proceeds", async () => {
|
||||||
|
invalidateCachesForUser("u1");
|
||||||
|
jest.spyOn(Models.TeamMembership, "find").mockReturnValue({ select: () => ({ lean: () => [{ teamId: { toString: () => "t-1" } }] }) });
|
||||||
|
// roles already mocked in beforeEach
|
||||||
|
|
||||||
|
const req = mockReq({ sub: "u1", orgId: "o1" }, { "x-team-id": "t-1" });
|
||||||
|
const res = mockRes();
|
||||||
|
const next = mockNext();
|
||||||
|
await addUserContext(req, res, next);
|
||||||
|
expect(next).toHaveBeenCalled();
|
||||||
|
expect(req.user.roles.orgRole).toEqual({ name: "org-role" });
|
||||||
|
expect(req.user.roles.teamRole).toEqual({ name: "team-role" });
|
||||||
|
expect(req.user.currentTeamId).toBe("t-1");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
jest.mock("got", () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: { post: jest.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
import DiscordService from "@/services/infrastructure/NotificationServices/Discord.js";
|
||||||
|
import ApiError from "@/utils/ApiError.js";
|
||||||
|
|
||||||
|
const getGot = () => jest.requireMock("got").default;
|
||||||
|
|
||||||
|
const buildChannel = (overrides = {}) => ({
|
||||||
|
_id: "c1",
|
||||||
|
name: "Discord",
|
||||||
|
type: "discord",
|
||||||
|
config: { url: "https://discordapp.com/api/webhooks/XXX" },
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const buildMonitor = (overrides = {}) => ({ name: "m", status: "up", url: "u", ...overrides });
|
||||||
|
const buildIncident = (overrides = {}) => ({ resolved: false, ...overrides });
|
||||||
|
|
||||||
|
describe("DiscordService", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
getGot().post.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends message via webhook", async () => {
|
||||||
|
const service = new DiscordService();
|
||||||
|
getGot().post.mockResolvedValue({});
|
||||||
|
const channel = buildChannel();
|
||||||
|
const alert = service.buildAlert(buildMonitor(), buildIncident());
|
||||||
|
const ok = await service.sendMessage(alert, channel);
|
||||||
|
expect(getGot().post).toHaveBeenCalled();
|
||||||
|
expect(ok).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws when url missing", async () => {
|
||||||
|
const service = new DiscordService();
|
||||||
|
const channel = buildChannel({ config: {} });
|
||||||
|
const alert = service.buildAlert(buildMonitor(), buildIncident());
|
||||||
|
await expect(service.sendMessage(alert, channel)).rejects.toBeInstanceOf(ApiError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
jest.mock("nodemailer", () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: {
|
||||||
|
createTransport: jest.fn(() => ({
|
||||||
|
sendMail: jest.fn().mockResolvedValue({})
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
import EmailService from "@/services/infrastructure/NotificationServices/Email.js";
|
||||||
|
|
||||||
|
// Mock user service to avoid calling getAllUsers
|
||||||
|
const userServiceMock = { getAllUsers: jest.fn().mockResolvedValue([{ email: "a@example.com" }]) };
|
||||||
|
// Settings service mock (unused path in test)
|
||||||
|
const settingsServiceMock = {};
|
||||||
|
|
||||||
|
const getMailer = () => jest.requireMock("nodemailer").default;
|
||||||
|
|
||||||
|
const buildChannel = (overrides = {}) => ({
|
||||||
|
_id: "c1",
|
||||||
|
name: "Email",
|
||||||
|
type: "email",
|
||||||
|
config: { emailAddress: "alerts@example.com" },
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const buildMonitor = (overrides = {}) => ({ name: "m", status: "up", url: "u", ...overrides });
|
||||||
|
const buildIncident = (overrides = {}) => ({ resolved: false, ...overrides });
|
||||||
|
|
||||||
|
describe("EmailService", () => {
|
||||||
|
it("sends test message", async () => {
|
||||||
|
const service = new EmailService(userServiceMock , settingsServiceMock);
|
||||||
|
// Force transporter build
|
||||||
|
getMailer().createTransport.mockReturnValue({ sendMail: jest.fn().mockResolvedValue({}) });
|
||||||
|
// ensure we bypass env SMTP path
|
||||||
|
const ok = await service.testMessage(buildChannel());
|
||||||
|
expect(ok).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -30,6 +30,30 @@ jest.mock("cacheable-lookup", () => ({
|
|||||||
jest.mock("ping", () => ({
|
jest.mock("ping", () => ({
|
||||||
promise: { probe: jest.fn() },
|
promise: { probe: jest.fn() },
|
||||||
}));
|
}));
|
||||||
|
// Mock net for requestPort tests
|
||||||
|
jest.mock("net", () => {
|
||||||
|
const listeners = new Map();
|
||||||
|
const socket = {
|
||||||
|
setTimeout: jest.fn(),
|
||||||
|
on: jest.fn((event, cb) => {
|
||||||
|
listeners.set(event, cb);
|
||||||
|
return socket;
|
||||||
|
}),
|
||||||
|
destroy: jest.fn(),
|
||||||
|
__emit: (event, arg) => {
|
||||||
|
const cb = listeners.get(event);
|
||||||
|
if (cb) cb(arg);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
__esModule: true,
|
||||||
|
default: {
|
||||||
|
createConnection: jest.fn(() => socket),
|
||||||
|
__socket: socket,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const getNetModule = () => jest.requireMock("net").default;
|
||||||
const getGotModule = () => jest.requireMock("got");
|
const getGotModule = () => jest.requireMock("got");
|
||||||
const buildMonitor = (overrides = {}) => ({
|
const buildMonitor = (overrides = {}) => ({
|
||||||
_id: new Types.ObjectId(),
|
_id: new Types.ObjectId(),
|
||||||
@@ -134,6 +158,28 @@ describe("NetworkService.buildStatusResponse", () => {
|
|||||||
expect(result.responseTime).toBe(987);
|
expect(result.responseTime).toBe(987);
|
||||||
expect(result.timings).toBe(timings);
|
expect(result.timings).toBe(timings);
|
||||||
});
|
});
|
||||||
|
it("handles HTTPError without timings/statusCode", () => {
|
||||||
|
const { service, gotModule } = createService();
|
||||||
|
const { HTTPError } = gotModule;
|
||||||
|
const monitor = buildMonitor();
|
||||||
|
const httpError = new HTTPError("Boom", {});
|
||||||
|
const result = invokeBuildStatusResponse(service, monitor, null, httpError);
|
||||||
|
expect(result.status).toBe("down");
|
||||||
|
expect(result.code).toBe(5000);
|
||||||
|
expect(result.message).toBe("Boom");
|
||||||
|
expect(result.responseTime).toBe(0);
|
||||||
|
// When no timings exist on HTTPError, we do not attach timings.
|
||||||
|
expect(result.timings).toBeUndefined();
|
||||||
|
});
|
||||||
|
it("defaults timings when missing on successful response", () => {
|
||||||
|
const { service } = createService();
|
||||||
|
const monitor = buildMonitor();
|
||||||
|
const response = { statusCode: 200, ok: true };
|
||||||
|
const result = invokeBuildStatusResponse(service, monitor, response, null);
|
||||||
|
expect(result.status).toBe("up");
|
||||||
|
expect(result.timings).toEqual({ phases: {} });
|
||||||
|
expect(result.responseTime).toBe(0);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
describe("NetworkService.requestHttp", () => {
|
describe("NetworkService.requestHttp", () => {
|
||||||
it("requests monitor URL and maps successful response", async () => {
|
it("requests monitor URL and maps successful response", async () => {
|
||||||
@@ -367,6 +413,25 @@ describe("NetworkService.requestPagespeed", () => {
|
|||||||
responseType: "json",
|
responseType: "json",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
it("returns down status when primary response is not ok but still attaches payload", async () => {
|
||||||
|
const primaryResponse = {
|
||||||
|
statusCode: 500,
|
||||||
|
statusMessage: "Server Error",
|
||||||
|
ok: false,
|
||||||
|
};
|
||||||
|
const payload = { lighthouseResult: { score: 0.7 } };
|
||||||
|
const secondaryResponse = { body: payload };
|
||||||
|
const requestMock = jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(primaryResponse)
|
||||||
|
.mockResolvedValueOnce(secondaryResponse);
|
||||||
|
const { service } = createService(requestMock);
|
||||||
|
const monitor = buildMonitor({ type: "pagespeed", url: "https://x" });
|
||||||
|
const result = await service.requestPagespeed(monitor);
|
||||||
|
expect(result.status).toBe("down");
|
||||||
|
expect(result.code).toBe(500);
|
||||||
|
expect(result.payload).toBe(payload);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
describe("NetworkService.requestPing", () => {
|
describe("NetworkService.requestPing", () => {
|
||||||
it("maps successful ping with string time", async () => {
|
it("maps successful ping with string time", async () => {
|
||||||
@@ -406,6 +471,51 @@ describe("NetworkService.requestPing", () => {
|
|||||||
expect(result.status).toBe("up");
|
expect(result.status).toBe("up");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("NetworkService.requestPort", () => {
|
||||||
|
it("returns default response when port missing", async () => {
|
||||||
|
const { service } = createService();
|
||||||
|
const monitor = buildMonitor({ type: "port", url: "localhost", port: undefined });
|
||||||
|
const result = await service.requestPort(monitor);
|
||||||
|
expect(result.status).toBe("down");
|
||||||
|
expect(result.message).toBe("Port check failed");
|
||||||
|
expect(result.responseTime).toBe(0);
|
||||||
|
});
|
||||||
|
it("resolves up on connect event", async () => {
|
||||||
|
const { service } = createService();
|
||||||
|
const netModule = getNetModule();
|
||||||
|
const monitor = buildMonitor({ type: "port", url: "localhost", port: 80 });
|
||||||
|
const promise = service.requestPort(monitor);
|
||||||
|
// Emit connect
|
||||||
|
netModule.__socket.__emit("connect");
|
||||||
|
const result = await promise;
|
||||||
|
expect(result.status).toBe("up");
|
||||||
|
expect(result.message).toBe("Port is open");
|
||||||
|
expect(result.responseTime).toBeGreaterThanOrEqual(0);
|
||||||
|
});
|
||||||
|
it("resolves down on error event", async () => {
|
||||||
|
const { service } = createService();
|
||||||
|
const netModule = getNetModule();
|
||||||
|
const monitor = buildMonitor({ type: "port", url: "localhost", port: 81 });
|
||||||
|
const promise = service.requestPort(monitor);
|
||||||
|
netModule.__socket.__emit("error", new Error("ECONNREFUSED"));
|
||||||
|
const result = await promise;
|
||||||
|
expect(result.status).toBe("down");
|
||||||
|
expect(result.message).toBe("ECONNREFUSED");
|
||||||
|
expect(result.responseTime).toBeGreaterThanOrEqual(0);
|
||||||
|
});
|
||||||
|
it("resolves down on timeout event", async () => {
|
||||||
|
const { service } = createService();
|
||||||
|
const netModule = getNetModule();
|
||||||
|
const monitor = buildMonitor({ type: "port", url: "localhost", port: 82 });
|
||||||
|
const promise = service.requestPort(monitor);
|
||||||
|
netModule.__socket.__emit("timeout");
|
||||||
|
const result = await promise;
|
||||||
|
expect(result.status).toBe("down");
|
||||||
|
expect(result.message).toBe("Port check timed out");
|
||||||
|
expect(result.responseTime).toBeGreaterThanOrEqual(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
describe("NetworkService.requestStatus", () => {
|
describe("NetworkService.requestStatus", () => {
|
||||||
it("routes http monitors through requestHttp", async () => {
|
it("routes http monitors through requestHttp", async () => {
|
||||||
const { service } = createService();
|
const { service } = createService();
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
// Mock HTTP client used by notification transports to avoid ESM import issues
|
||||||
|
jest.mock("got", () => {
|
||||||
|
const extend = jest.fn(() => jest.fn());
|
||||||
|
return { __esModule: true, default: { extend } };
|
||||||
|
});
|
||||||
|
|
||||||
|
import NotificationService from "@/services/infrastructure/NotificationService.js";
|
||||||
|
import {
|
||||||
|
EmailService,
|
||||||
|
SlackService,
|
||||||
|
DiscordService,
|
||||||
|
WebhookService,
|
||||||
|
} from "@/services/infrastructure/NotificationServices/index.js";
|
||||||
|
import { Monitor, NotificationChannel } from "@/db/models/index.js";
|
||||||
|
import ApiError from "@/utils/ApiError.js";
|
||||||
|
|
||||||
|
// Helper builders
|
||||||
|
const buildMonitor = (overrides = {}) => ({
|
||||||
|
_id: "m1",
|
||||||
|
teamId: "t1",
|
||||||
|
name: "My Monitor",
|
||||||
|
status: "up",
|
||||||
|
notificationChannels: [],
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const buildChannel = (overrides = {}) => ({
|
||||||
|
_id: "c1",
|
||||||
|
name: "Email Alerts",
|
||||||
|
type: "email",
|
||||||
|
config: { emailAddress: "alerts@example.com", url: "" },
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create a concrete service instance using real constructor (deps are not used directly here)
|
||||||
|
const createService = () =>
|
||||||
|
new NotificationService({} /** UserService */, {} /** SettingsService */);
|
||||||
|
|
||||||
|
describe("NotificationService.testEmailTransport", () => {
|
||||||
|
it("delegates to EmailService.testTransport", async () => {
|
||||||
|
const service = createService();
|
||||||
|
const spy = jest
|
||||||
|
.spyOn(service["emailService"], "testTransport")
|
||||||
|
.mockResolvedValue(true);
|
||||||
|
const result = await service.testEmailTransport({
|
||||||
|
systemEmailSecure: false,
|
||||||
|
systemEmailPool: false,
|
||||||
|
systemEmailIgnoreTLS: false,
|
||||||
|
systemEmailRequireTLS: false,
|
||||||
|
systemEmailRejectUnauthorized: true,
|
||||||
|
});
|
||||||
|
expect(spy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("NotificationService.testNotificationChannel", () => {
|
||||||
|
afterEach(() => jest.restoreAllMocks());
|
||||||
|
|
||||||
|
it("tests email channel and returns sent flag", async () => {
|
||||||
|
const service = createService();
|
||||||
|
jest.spyOn(service["emailService"], "testMessage").mockResolvedValue(true);
|
||||||
|
const channel = buildChannel({
|
||||||
|
type: "email",
|
||||||
|
config: { emailAddress: "x@example.com" },
|
||||||
|
});
|
||||||
|
const sent = await service.testNotificationChannel(channel);
|
||||||
|
expect(sent).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tests slack/discord/webhook channels and returns sent flag", async () => {
|
||||||
|
const service = createService();
|
||||||
|
jest.spyOn(service["slackService"], "testMessage").mockResolvedValue(true);
|
||||||
|
jest
|
||||||
|
.spyOn(service["discordService"], "testMessage")
|
||||||
|
.mockResolvedValue(false);
|
||||||
|
jest
|
||||||
|
.spyOn(service["webhookService"], "testMessage")
|
||||||
|
.mockResolvedValue(true);
|
||||||
|
|
||||||
|
const slack = buildChannel({
|
||||||
|
_id: "c2",
|
||||||
|
type: "slack",
|
||||||
|
config: { url: "https://hooks.slack.com/.." },
|
||||||
|
});
|
||||||
|
const discord = buildChannel({
|
||||||
|
_id: "c3",
|
||||||
|
type: "discord",
|
||||||
|
config: { url: "https://discordapp.com/api/webhooks/..." },
|
||||||
|
});
|
||||||
|
const webhook = buildChannel({
|
||||||
|
_id: "c4",
|
||||||
|
type: "webhook",
|
||||||
|
config: { url: "https://example.com/hook" },
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.testNotificationChannel(slack)).resolves.toBe(true);
|
||||||
|
await expect(service.testNotificationChannel(discord)).resolves.toBe(false);
|
||||||
|
await expect(service.testNotificationChannel(webhook)).resolves.toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("NotificationService.testNotificationChannels", () => {
|
||||||
|
afterEach(() => jest.restoreAllMocks());
|
||||||
|
|
||||||
|
it("throws 404 when monitor missing", async () => {
|
||||||
|
const service = createService();
|
||||||
|
jest.spyOn(Monitor, "findOne").mockResolvedValue(null);
|
||||||
|
await expect(
|
||||||
|
service.testNotificationChannels("m1", "t1")
|
||||||
|
).rejects.toBeInstanceOf(ApiError);
|
||||||
|
await expect(
|
||||||
|
service.testNotificationChannels("m1", "t1")
|
||||||
|
).rejects.toMatchObject({ status: 404 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("aggregates results for all channels", async () => {
|
||||||
|
const service = createService();
|
||||||
|
const monitor = buildMonitor({
|
||||||
|
notificationChannels: ["c1", "c2", "c3", "c4"],
|
||||||
|
});
|
||||||
|
jest.spyOn(Monitor, "findOne").mockResolvedValue(monitor);
|
||||||
|
const channels = [
|
||||||
|
buildChannel({
|
||||||
|
_id: "c1",
|
||||||
|
type: "email",
|
||||||
|
config: { emailAddress: "a@example.com" },
|
||||||
|
}),
|
||||||
|
buildChannel({
|
||||||
|
_id: "c2",
|
||||||
|
type: "slack",
|
||||||
|
config: { url: "https://slack" },
|
||||||
|
}),
|
||||||
|
buildChannel({
|
||||||
|
_id: "c3",
|
||||||
|
type: "discord",
|
||||||
|
config: { url: "https://discord" },
|
||||||
|
}),
|
||||||
|
buildChannel({
|
||||||
|
_id: "c4",
|
||||||
|
type: "webhook",
|
||||||
|
config: { url: "https://webhook" },
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
jest
|
||||||
|
.spyOn(NotificationChannel, "find")
|
||||||
|
.mockReturnValue({ lean: () => channels });
|
||||||
|
jest.spyOn(service["emailService"], "testMessage").mockResolvedValue(true);
|
||||||
|
jest.spyOn(service["slackService"], "testMessage").mockResolvedValue(false);
|
||||||
|
jest
|
||||||
|
.spyOn(service["discordService"], "testMessage")
|
||||||
|
.mockResolvedValue(true);
|
||||||
|
jest
|
||||||
|
.spyOn(service["webhookService"], "testMessage")
|
||||||
|
.mockResolvedValue(true);
|
||||||
|
|
||||||
|
const results = await service.testNotificationChannels("m1", "t1");
|
||||||
|
expect(Array.isArray(results)).toBe(true);
|
||||||
|
expect(results).toHaveLength(4);
|
||||||
|
const byType = Object.fromEntries(
|
||||||
|
results.map((r) => [r.channelType, r.sent])
|
||||||
|
);
|
||||||
|
expect(byType.email).toBe(true);
|
||||||
|
expect(byType.slack).toBe(false);
|
||||||
|
expect(byType.discord).toBe(true);
|
||||||
|
expect(byType.webhook).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("NotificationService.handleNotifications", () => {
|
||||||
|
afterEach(() => jest.restoreAllMocks());
|
||||||
|
|
||||||
|
it("returns early when no channels configured", async () => {
|
||||||
|
const service = createService();
|
||||||
|
const monitor = buildMonitor({ notificationChannels: [] });
|
||||||
|
await expect(
|
||||||
|
service.handleNotifications(monitor, { _id: "i1" })
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("invokes appropriate service by channel type", async () => {
|
||||||
|
const service = createService();
|
||||||
|
const monitor = buildMonitor({
|
||||||
|
notificationChannels: ["c1", "c2", "c3", "c4"],
|
||||||
|
});
|
||||||
|
const channelDocs = [
|
||||||
|
buildChannel({
|
||||||
|
_id: "c1",
|
||||||
|
type: "email",
|
||||||
|
config: { emailAddress: "a@example.com" },
|
||||||
|
}),
|
||||||
|
buildChannel({
|
||||||
|
_id: "c2",
|
||||||
|
type: "slack",
|
||||||
|
config: { url: "https://slack" },
|
||||||
|
}),
|
||||||
|
buildChannel({
|
||||||
|
_id: "c3",
|
||||||
|
type: "discord",
|
||||||
|
config: { url: "https://discord" },
|
||||||
|
}),
|
||||||
|
buildChannel({
|
||||||
|
_id: "c4",
|
||||||
|
type: "webhook",
|
||||||
|
config: { url: "https://webhook" },
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
jest.spyOn(NotificationChannel, "find").mockResolvedValue(channelDocs);
|
||||||
|
|
||||||
|
const emailSpy = jest
|
||||||
|
.spyOn(service["emailService"], "sendMessage")
|
||||||
|
.mockResolvedValue(true);
|
||||||
|
const slackSpy = jest
|
||||||
|
.spyOn(service["slackService"], "sendMessage")
|
||||||
|
.mockResolvedValue(true);
|
||||||
|
const discordSpy = jest
|
||||||
|
.spyOn(service["discordService"], "sendMessage")
|
||||||
|
.mockResolvedValue(true);
|
||||||
|
const webhookSpy = jest
|
||||||
|
.spyOn(service["webhookService"], "sendMessage")
|
||||||
|
.mockResolvedValue(true);
|
||||||
|
|
||||||
|
await service.handleNotifications(monitor, { _id: "i1", monitorId: "m1" });
|
||||||
|
|
||||||
|
expect(emailSpy).toHaveBeenCalled();
|
||||||
|
expect(slackSpy).toHaveBeenCalled();
|
||||||
|
expect(discordSpy).toHaveBeenCalled();
|
||||||
|
expect(webhookSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
jest.mock("got", () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: { post: jest.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
import SlackService from "@/services/infrastructure/NotificationServices/Slack.js";
|
||||||
|
|
||||||
|
const getGot = () => jest.requireMock("got").default;
|
||||||
|
|
||||||
|
const buildChannel = (overrides = {}) => ({
|
||||||
|
_id: "c1",
|
||||||
|
name: "Slack",
|
||||||
|
type: "slack",
|
||||||
|
config: { url: "https://hooks.slack.com/services/T000/B000/XXX" },
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const buildMonitor = (overrides = {}) => ({ name: "m", status: "up", url: "u", ...overrides });
|
||||||
|
const buildIncident = (overrides = {}) => ({ resolved: false, ...overrides });
|
||||||
|
|
||||||
|
describe("SlackService", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
getGot().post.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends message via webhook", async () => {
|
||||||
|
const service = new SlackService();
|
||||||
|
getGot().post.mockResolvedValue({});
|
||||||
|
const channel = buildChannel();
|
||||||
|
const alert = service.buildAlert(buildMonitor(), buildIncident());
|
||||||
|
const ok = await service.sendMessage(alert, channel);
|
||||||
|
expect(getGot().post).toHaveBeenCalled();
|
||||||
|
expect(ok).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws when url missing", async () => {
|
||||||
|
const service = new SlackService();
|
||||||
|
const channel = buildChannel({ config: {} });
|
||||||
|
const alert = service.buildAlert(buildMonitor(), buildIncident());
|
||||||
|
await expect(service.sendMessage(alert, channel)).rejects.toThrow("Webhook URL not configured");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
jest.mock("got", () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: { post: jest.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
import WebhookService from "@/services/infrastructure/NotificationServices/Webhook.js";
|
||||||
|
import ApiError from "@/utils/ApiError.js";
|
||||||
|
|
||||||
|
const getGot = () => jest.requireMock("got").default;
|
||||||
|
|
||||||
|
const buildChannel = (overrides = {}) => ({
|
||||||
|
_id: "c1",
|
||||||
|
name: "Webhook",
|
||||||
|
type: "webhook",
|
||||||
|
config: { url: "https://example.com/hook" },
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const buildMonitor = (overrides = {}) => ({ name: "m", status: "up", url: "u", ...overrides });
|
||||||
|
const buildIncident = (overrides = {}) => ({ resolved: false, ...overrides });
|
||||||
|
|
||||||
|
describe("WebhookService", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
getGot().post.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends message via webhook", async () => {
|
||||||
|
const service = new WebhookService();
|
||||||
|
getGot().post.mockResolvedValue({});
|
||||||
|
const channel = buildChannel();
|
||||||
|
const alert = service.buildAlert(buildMonitor(), buildIncident());
|
||||||
|
const ok = await service.sendMessage(alert, channel);
|
||||||
|
expect(getGot().post).toHaveBeenCalled();
|
||||||
|
expect(ok).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws when url missing", async () => {
|
||||||
|
const service = new WebhookService();
|
||||||
|
const channel = buildChannel({ config: {} });
|
||||||
|
const alert = service.buildAlert(buildMonitor(), buildIncident());
|
||||||
|
await expect(service.sendMessage(alert, channel)).rejects.toBeInstanceOf(ApiError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
Reference in new issue
Block a user