improve test coverage

This commit is contained in:
Alex Holliday committed 2025-11-24 22:49:55 +00:00
1 parent d5f1032bdf
commit 1e26fb1e3b
15 files changed
+388 -71

No files matched your search

@@ -50,4 +50,59 @@ describe("addUserContext", () => {
expect(req.user.roles.teamRole).toEqual({ name: "team-role" });
expect(req.user.currentTeamId).toBe("t-1");
});
it("uses cached teamIds and roles when cache valid", async () => {
// First call populates cache
jest.spyOn(Models.TeamMembership, "find").mockReturnValue({ select: () => ({ lean: () => [{ teamId: { toString: () => "t-1" } }] }) });
const req1 = mockReq({ sub: "u-cache", orgId: "o1" }, { "x-team-id": "t-1" });
const next1 = mockNext();
await addUserContext(req1, mockRes(), next1);
expect(next1).toHaveBeenCalled();
// Second call should hit cache and still succeed; mock find to fail if called
jest.spyOn(Models.TeamMembership, "find").mockImplementation(() => { throw new Error("should not query"); });
const req2 = mockReq({ sub: "u-cache", orgId: "o1" }, { "x-team-id": "t-1" });
const next2 = mockNext();
await addUserContext(req2, mockRes(), next2);
expect(next2).toHaveBeenCalled();
});
it("invalidates caches for user", async () => {
// Warm caches
jest.spyOn(Models.TeamMembership, "find").mockReturnValue({ select: () => ({ lean: () => [{ teamId: { toString: () => "t-1" } }] }) });
const req = mockReq({ sub: "u-inv", orgId: "o1" }, { "x-team-id": "t-1" });
const next = mockNext();
await addUserContext(req, mockRes(), next);
expect(next).toHaveBeenCalled();
// Invalidate and ensure it re-queries without throwing
invalidateCachesForUser("u-inv");
jest.spyOn(Models.TeamMembership, "find").mockReturnValue({ select: () => ({ lean: () => [{ teamId: { toString: () => "t-1" } }] }) });
const next2 = mockNext();
await addUserContext(mockReq({ sub: "u-inv", orgId: "o1" }, { "x-team-id": "t-1" }), mockRes(), next2);
expect(next2).toHaveBeenCalled();
});
it("throws when org role missing", async () => {
jest.spyOn(Models.TeamMembership, "find").mockReturnValue({ select: () => ({ lean: () => [{ teamId: { toString: () => "t-1" } }] }) });
jest.spyOn(Models.OrgMembership, "findOne").mockReturnValue({ populate: () => ({ select: () => ({ lean: () => null }) }) });
const req = mockReq({ sub: "u2", orgId: "o1" }, { "x-team-id": "t-1" });
const next = mockNext();
await addUserContext(req, mockRes(), next);
const err = next.mock.calls[0][0];
expect(err).toBeInstanceOf(ApiError);
expect(err.status).toBe(403);
});
it("throws when team role missing", async () => {
jest.spyOn(Models.TeamMembership, "find").mockReturnValue({ select: () => ({ lean: () => [{ teamId: { toString: () => "t-1" } }] }) });
jest.spyOn(Models.OrgMembership, "findOne").mockReturnValue({ populate: () => ({ select: () => ({ lean: () => ({ roleId: { name: "org-role" } }) }) }) });
jest.spyOn(Models.TeamMembership, "findOne").mockReturnValue({ populate: () => ({ select: () => ({ lean: () => null }) }) });
const req = mockReq({ sub: "u3", orgId: "o1" }, { "x-team-id": "t-1" });
const next = mockNext();
await addUserContext(req, mockRes(), next);
const err = next.mock.calls[0][0];
expect(err).toBeInstanceOf(ApiError);
expect(err.status).toBe(403);
});
});
@@ -40,5 +40,29 @@ describe("DiscordService", () => {
const alert = service.buildAlert(buildMonitor(), buildIncident());
await expect(service.sendMessage(alert, channel)).rejects.toBeInstanceOf(ApiError);
});
});
it("returns false when webhook post fails", async () => {
const service = new (await import("@/services/infrastructure/NotificationServices/Discord.js")).default();
const getGot = () => jest.requireMock("got").default;
getGot().post.mockRejectedValue(new Error("net"));
const channel = buildChannel();
const alert = service.buildAlert(buildMonitor(), buildIncident());
const ok = await service.sendMessage(alert, channel);
expect(ok).toBe(false);
});
it("uses red color embed when status is down", async () => {
const service = new DiscordService();
const getGot = () => jest.requireMock("got").default;
getGot().post.mockResolvedValue({});
const channel = buildChannel();
const alert = service.buildAlert(
buildMonitor({ status: "down" }),
buildIncident()
);
await service.sendMessage(alert, channel);
const call = getGot().post.mock.calls[0];
const payload = call[1].json;
expect(payload.embeds[0].color).toBe(16711680);
});
});
@@ -2,9 +2,19 @@ jest.mock("nodemailer", () => ({
__esModule: true,
default: {
createTransport: jest.fn(() => ({
sendMail: jest.fn().mockResolvedValue({})
}))
}
sendMail: jest.fn().mockResolvedValue({}),
})),
},
}));
// Default: no env SMTP so system-settings path is used unless overridden per-test
jest.mock("@/config/index.js", () => ({
config: {
SMTP_HOST: "not_set",
SMTP_PORT: -1,
SMTP_USER: "not_set",
SMTP_PASS: "not_set",
},
}));
import EmailService from "@/services/infrastructure/NotificationServices/Email.js";
@@ -12,7 +22,22 @@ import EmailService from "@/services/infrastructure/NotificationServices/Email.j
// 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 settingsServiceMock = {
get: jest.fn().mockResolvedValue({
systemEmailHost: "smtp.example.com",
systemEmailPort: 587,
systemEmailAddress: "noreply@example.com",
systemEmailUser: "smtp-user",
systemEmailPassword: "smtp-pass",
systemEmailConnectionHost: "example.com",
systemEmailTLSServername: "example.com",
systemEmailSecure: false,
systemEmailPool: false,
systemEmailIgnoreTLS: false,
systemEmailRequireTLS: false,
systemEmailRejectUnauthorized: true,
}),
};
const getMailer = () => jest.requireMock("nodemailer").default;
@@ -36,4 +61,100 @@ describe("EmailService", () => {
const ok = await service.testMessage(buildChannel());
expect(ok).toBe(true);
});
it("uses system settings transport (no env) and sendGeneric succeeds", async () => {
const service = new EmailService(userServiceMock, settingsServiceMock);
const mailer = getMailer();
const sendMail = jest.fn().mockResolvedValue({});
mailer.createTransport.mockReturnValue({ sendMail });
const ok = await service.sendGeneric("to@example.com", "Subj", "Body");
expect(ok).toBe(true);
expect(mailer.createTransport).toHaveBeenCalled();
const arg = mailer.createTransport.mock.calls[0][0];
expect(arg.host || arg?.host === undefined).toBeDefined();
});
it("returns false when no user emails found in sendMessage", async () => {
const service = new EmailService({ getAllUsers: jest.fn().mockResolvedValue([]) }, settingsServiceMock);
const ok = await service.sendMessage({ name: "n", url: "u", status: "s", checkTime: new Date(), alertTime: new Date(), resolved: false }, buildChannel());
expect(ok).toBe(false);
});
it("rebuildTransport sets transporter and from and returns true", async () => {
const service = new EmailService(userServiceMock, settingsServiceMock);
const mailer = getMailer();
const sendMail = jest.fn().mockResolvedValue({});
mailer.createTransport.mockReturnValue({ sendMail });
const res = await service.rebuildTransport({
systemEmailHost: "smtp.example.com",
systemEmailPort: 465,
systemEmailAddress: "noreply@example.com",
systemEmailUser: "smtp-user",
systemEmailPassword: "smtp-pass",
systemEmailSecure: true,
systemEmailPool: true,
systemEmailIgnoreTLS: false,
systemEmailRequireTLS: false,
systemEmailRejectUnauthorized: true,
});
expect(res).toBe(true);
expect(mailer.createTransport).toHaveBeenCalled();
});
it("testTransport throws when env SMTP configured", async () => {
jest.resetModules();
jest.doMock("@/config/index.js", () => ({
config: { SMTP_HOST: "smtp.env", SMTP_PORT: 465, SMTP_USER: "u", SMTP_PASS: "p" },
}));
const { default: EmailServiceEnv } = await import("@/services/infrastructure/NotificationServices/Email.js");
const service = new EmailServiceEnv(userServiceMock, settingsServiceMock);
await expect(
service.testTransport({ systemEmailAddress: "noreply@example.com", systemEmailSecure: false, systemEmailPool: false, systemEmailIgnoreTLS: false, systemEmailRequireTLS: false, systemEmailRejectUnauthorized: true })
).rejects.toMatchObject({ status: 400 });
});
it("builds env transport when env present and uses secure flag", async () => {
jest.resetModules();
jest.doMock("@/config/index.js", () => ({
config: { SMTP_HOST: "smtp.env", SMTP_PORT: 465, SMTP_USER: "u", SMTP_PASS: "p" },
}));
const { default: EmailServiceEnv } = await import("@/services/infrastructure/NotificationServices/Email.js");
const mailer = getMailer();
mailer.createTransport.mockReturnValue({ sendMail: jest.fn().mockResolvedValue({}) });
const service = new EmailServiceEnv(userServiceMock, settingsServiceMock);
await service.sendGeneric("t@example.com", "s", "b");
expect(mailer.createTransport).toHaveBeenCalledWith(
expect.objectContaining({ host: "smtp.env", port: 465, secure: true })
);
});
it("sendGeneric rejects when transporter sendMail fails", async () => {
const service = new EmailService(userServiceMock, settingsServiceMock);
// Bypass nodemailer mock by injecting a failing transporter directly
service.transporter = { sendMail: jest.fn().mockRejectedValue(new Error("fail")) };
await expect(service.sendGeneric("t@example.com", "s", "b")).rejects.toBeInstanceOf(Error);
});
it("testTransport throws ApiError when sendMail fails", async () => {
const service = new EmailService(userServiceMock, settingsServiceMock);
// Force buildSystemSettingsTransport to return a transporter whose sendMail fails
service.buildSystemSettingsTransport = jest
.fn()
.mockResolvedValue({ sendMail: jest.fn().mockRejectedValue(new Error("smtp-fail")) });
await expect(
service.testTransport({
systemEmailHost: "smtp.example.com",
systemEmailPort: 587,
systemEmailAddress: "noreply@example.com",
systemEmailUser: "smtp-user",
systemEmailPassword: "smtp-pass",
systemEmailSecure: false,
systemEmailPool: false,
systemEmailIgnoreTLS: false,
systemEmailRequireTLS: false,
systemEmailRejectUnauthorized: true,
})
).rejects.toMatchObject({ status: 400 });
});
});
@@ -165,6 +165,24 @@ describe("NotificationService.testNotificationChannels", () => {
expect(byType.discord).toBe(true);
expect(byType.webhook).toBe(true);
});
it("uses 'N/A' for missing channel URLs/emails in results", async () => {
const service = createService();
const monitor = buildMonitor({ notificationChannels: ["c1", "c2"] });
jest.spyOn(Monitor, "findOne").mockResolvedValue(monitor);
const channels = [
buildChannel({ _id: "c1", type: "slack", config: {} }),
buildChannel({ _id: "c2", type: "email", config: {} }),
];
jest.spyOn(NotificationChannel, "find").mockReturnValue({ lean: () => channels });
jest.spyOn(service["slackService"], "testMessage").mockResolvedValue(true);
jest.spyOn(service["emailService"], "testMessage").mockResolvedValue(true);
const results = await service.testNotificationChannels("m1", "t1");
const byType = Object.fromEntries(results.map((r) => [r.channelType, r.channelUrl]));
expect(byType.slack).toBe("N/A");
expect(byType.email).toBe("N/A");
});
});
describe("NotificationService.handleNotifications", () => {
@@ -227,4 +245,29 @@ describe("NotificationService.handleNotifications", () => {
expect(discordSpy).toHaveBeenCalled();
expect(webhookSpy).toHaveBeenCalled();
});
it("handles unknown channel types without throwing", async () => {
const service = createService();
const monitor = buildMonitor({ notificationChannels: ["cx"] });
jest
.spyOn(NotificationChannel, "find")
.mockResolvedValue([{ _id: "cx", type: "unknown", name: "u", config: {} }]);
await expect(
service.handleNotifications(monitor, { _id: "i1", monitorId: "m1" })
).resolves.toBeUndefined();
});
});
describe("NotificationService unknown channel branch", () => {
it("testNotificationChannel returns false for unknown type", async () => {
const service = createService();
const sent = await service.testNotificationChannel({
_id: "c-unknown",
type: "unknown",
name: "u",
config: {},
});
expect(sent).toBe(false);
});
});
@@ -39,4 +39,25 @@ describe("SlackService", () => {
const alert = service.buildAlert(buildMonitor(), buildIncident());
await expect(service.sendMessage(alert, channel)).rejects.toThrow("Webhook URL not configured");
});
it("returns false when webhook post fails", async () => {
const service = new SlackService();
getGot().post.mockRejectedValue(new Error("net"));
const channel = buildChannel();
const alert = service.buildAlert(buildMonitor(), buildIncident());
const ok = await service.sendMessage(alert, channel);
expect(ok).toBe(false);
});
it("includes resolution fields and timestamps in payload", async () => {
const service = new SlackService();
getGot().post.mockResolvedValue({});
const channel = buildChannel();
const incident = buildIncident({ resolved: true, resolutionType: "auto", resolutionNote: "n" });
const alert = service.buildAlert(buildMonitor(), incident);
await service.sendMessage(alert, channel);
const payload = getGot().post.mock.calls[0][1].json;
expect(payload.blocks.some((b) => JSON.stringify(b).includes("Resolution Type"))).toBe(true);
expect(payload.blocks.some((b) => JSON.stringify(b).includes("Checked at"))).toBe(true);
});
});
@@ -40,5 +40,27 @@ describe("WebhookService", () => {
const alert = service.buildAlert(buildMonitor(), buildIncident());
await expect(service.sendMessage(alert, channel)).rejects.toBeInstanceOf(ApiError);
});
});
it("returns false when webhook post fails", async () => {
const getGot = () => jest.requireMock("got").default;
getGot().post.mockRejectedValue(new Error("net"));
const service = new WebhookService();
const channel = buildChannel();
const alert = service.buildAlert(buildMonitor(), buildIncident());
const ok = await service.sendMessage(alert, channel);
expect(ok).toBe(false);
});
it("sends alert fields in JSON body", async () => {
const getGot = () => jest.requireMock("got").default;
getGot().post.mockResolvedValue({});
const service = new WebhookService();
const channel = buildChannel();
const alert = service.buildAlert(buildMonitor(), buildIncident());
await service.sendMessage(alert, channel);
const body = getGot().post.mock.calls[0][1].json;
expect(body.name).toBe(alert.name);
expect(body.status).toBe(alert.status);
expect(body.url).toBe(alert.url);
});
});