Merge pull request #980 from bluewave-labs/feat/be/email-service-tests
Feat/be/email service tests
This commit is contained in:
4 files changed
+387
-14
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"all": true,
|
"all": true,
|
||||||
"include": ["controllers/*.js", "utils/*.js"],
|
"include": ["controllers/*.js", "utils/*.js", "service/*.js"],
|
||||||
"exclude": ["**/*.test.js"],
|
"exclude": ["**/*.test.js"],
|
||||||
"reporter": ["html", "text", "lcov"],
|
"reporter": ["html", "text", "lcov"],
|
||||||
"sourceMap": false,
|
"sourceMap": false,
|
||||||
|
|||||||
+16
-1
@@ -21,7 +21,14 @@ import { connectDbAndRunServer } from "./configs/db.js";
|
|||||||
import queueRouter from "./routes/queueRoute.js";
|
import queueRouter from "./routes/queueRoute.js";
|
||||||
import JobQueue from "./service/jobQueue.js";
|
import JobQueue from "./service/jobQueue.js";
|
||||||
import NetworkService from "./service/networkService.js";
|
import NetworkService from "./service/networkService.js";
|
||||||
|
|
||||||
|
// Email service and dependencies
|
||||||
import EmailService from "./service/emailService.js";
|
import EmailService from "./service/emailService.js";
|
||||||
|
import nodemailer from "nodemailer";
|
||||||
|
import pkg from "handlebars";
|
||||||
|
const { compile } = pkg;
|
||||||
|
import mjml2html from "mjml";
|
||||||
|
|
||||||
import SettingsService from "./service/settingsService.js";
|
import SettingsService from "./service/settingsService.js";
|
||||||
import db from "./db/mongo/MongoDB.js";
|
import db from "./db/mongo/MongoDB.js";
|
||||||
import { fetchMonitorCertificate } from "./controllers/controllerUtils.js";
|
import { fetchMonitorCertificate } from "./controllers/controllerUtils.js";
|
||||||
@@ -133,7 +140,15 @@ const startApp = async () => {
|
|||||||
const settingsService = new SettingsService();
|
const settingsService = new SettingsService();
|
||||||
|
|
||||||
await settingsService.loadSettings();
|
await settingsService.loadSettings();
|
||||||
const emailService = new EmailService(settingsService);
|
const emailService = new EmailService(
|
||||||
|
settingsService,
|
||||||
|
fs,
|
||||||
|
path,
|
||||||
|
compile,
|
||||||
|
mjml2html,
|
||||||
|
nodemailer,
|
||||||
|
logger
|
||||||
|
);
|
||||||
const networkService = new NetworkService(db, emailService);
|
const networkService = new NetworkService(db, emailService);
|
||||||
const jobQueue = await JobQueue.createJobQueue(db, networkService, settingsService);
|
const jobQueue = await JobQueue.createJobQueue(db, networkService, settingsService);
|
||||||
|
|
||||||
|
|||||||
+152
-12
@@ -1,11 +1,6 @@
|
|||||||
import fs from "fs";
|
|
||||||
import path from "path";
|
|
||||||
import nodemailer from "nodemailer";
|
|
||||||
import pkg from "handlebars";
|
|
||||||
const { compile } = pkg;
|
|
||||||
import mjml2html from "mjml";
|
|
||||||
import logger from "../utils/logger.js";
|
|
||||||
import { fileURLToPath } from "url";
|
import { fileURLToPath } from "url";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
const __dirname = path.dirname(__filename);
|
const __dirname = path.dirname(__filename);
|
||||||
|
|
||||||
@@ -17,9 +12,24 @@ const SERVICE_NAME = "EmailService";
|
|||||||
class EmailService {
|
class EmailService {
|
||||||
/**
|
/**
|
||||||
* Constructs an instance of the EmailService, initializing template loaders and the email transporter.
|
* Constructs an instance of the EmailService, initializing template loaders and the email transporter.
|
||||||
|
<<<<<<< HEAD
|
||||||
|
* @param {Object} settingsService - The settings service to get email configuration.
|
||||||
|
* @param {Object} fs - The file system module.
|
||||||
|
* @param {Object} path - The path module.
|
||||||
|
* @param {Function} compile - The Handlebars compile function.
|
||||||
|
* @param {Function} mjml2html - The MJML to HTML conversion function.
|
||||||
|
* @param {Object} nodemailer - The nodemailer module.
|
||||||
|
* @param {Object} logger - The logger module.
|
||||||
*/
|
*/
|
||||||
constructor(settingsService) {
|
constructor(settingsService, fs, path, compile, mjml2html, nodemailer, logger) {
|
||||||
this.settingsService = settingsService;
|
this.settingsService = settingsService;
|
||||||
|
this.fs = fs;
|
||||||
|
this.path = path;
|
||||||
|
this.compile = compile;
|
||||||
|
this.mjml2html = mjml2html;
|
||||||
|
this.nodemailer = nodemailer;
|
||||||
|
this.logger = logger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads an email template from the filesystem.
|
* Loads an email template from the filesystem.
|
||||||
*
|
*
|
||||||
@@ -28,11 +38,14 @@ class EmailService {
|
|||||||
*/
|
*/
|
||||||
this.loadTemplate = (templateName) => {
|
this.loadTemplate = (templateName) => {
|
||||||
try {
|
try {
|
||||||
const templatePath = path.join(__dirname, `../templates/${templateName}.mjml`);
|
const templatePath = this.path.join(
|
||||||
const templateContent = fs.readFileSync(templatePath, "utf8");
|
__dirname,
|
||||||
return compile(templateContent);
|
`../templates/${templateName}.mjml`
|
||||||
|
);
|
||||||
|
const templateContent = this.fs.readFileSync(templatePath, "utf8");
|
||||||
|
return this.compile(templateContent);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error("Error loading Email templates", {
|
this.logger.error("Error loading Email templates", {
|
||||||
error,
|
error,
|
||||||
service: this.SERVICE_NAME,
|
service: this.SERVICE_NAME,
|
||||||
});
|
});
|
||||||
@@ -71,8 +84,113 @@ class EmailService {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
this.transporter = this.nodemailer.createTransport(emailConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asynchronously builds and sends an email using a specified template and context.
|
||||||
|
*
|
||||||
|
* @param {string} template - The name of the template to use for the email body.
|
||||||
|
* @param {Object} context - The data context to render the template with.
|
||||||
|
* @param {string} to - The recipient's email address.
|
||||||
|
* @param {string} subject - The subject of the email.
|
||||||
|
* @returns {Promise<string>} A promise that resolves to the messageId of the sent email.
|
||||||
|
*/
|
||||||
|
buildAndSendEmail = async (template, context, to, subject) => {
|
||||||
|
const buildHtml = async (template, context) => {
|
||||||
|
try {
|
||||||
|
const mjml = this.templateLookup[template](context);
|
||||||
|
const html = await this.mjml2html(mjml);
|
||||||
|
return html.html;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error("Error building Email HTML", {
|
||||||
|
=======
|
||||||
|
*/
|
||||||
|
constructor(settingsService) {
|
||||||
|
this.settingsService = settingsService;
|
||||||
|
/**
|
||||||
|
* Loads an email template from the filesystem.
|
||||||
|
*
|
||||||
|
* @param {string} templateName - The name of the template to load.
|
||||||
|
* @returns {Function} A compiled template function that can be used to generate HTML email content.
|
||||||
|
*/
|
||||||
|
this.loadTemplate = (templateName) => {
|
||||||
|
try {
|
||||||
|
const templatePath = path.join(__dirname, `../templates/${templateName}.mjml`);
|
||||||
|
const templateContent = fs.readFileSync(templatePath, "utf8");
|
||||||
|
return compile(templateContent);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error loading Email templates", {
|
||||||
|
error,
|
||||||
|
service: this.SERVICE_NAME,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A lookup object to access preloaded email templates.
|
||||||
|
* @type {Object.<string, Function>}
|
||||||
|
* TODO Load less used templates in their respective functions
|
||||||
|
*/
|
||||||
|
this.templateLookup = {
|
||||||
|
welcomeEmailTemplate: this.loadTemplate("welcomeEmail"),
|
||||||
|
employeeActivationTemplate: this.loadTemplate("employeeActivation"),
|
||||||
|
noIncidentsThisWeekTemplate: this.loadTemplate("noIncidentsThisWeek"),
|
||||||
|
serverIsDownTemplate: this.loadTemplate("serverIsDown"),
|
||||||
|
serverIsUpTemplate: this.loadTemplate("serverIsUp"),
|
||||||
|
passwordResetTemplate: this.loadTemplate("passwordReset"),
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* A lookup object to access preloaded email templates.
|
||||||
|
* @type {Object.<string, Function>}
|
||||||
|
* TODO Load less used templates in their respective functions
|
||||||
|
*/
|
||||||
|
this.templateLookup = {
|
||||||
|
welcomeEmailTemplate: this.loadTemplate("welcomeEmail"),
|
||||||
|
employeeActivationTemplate: this.loadTemplate("employeeActivation"),
|
||||||
|
noIncidentsThisWeekTemplate: this.loadTemplate("noIncidentsThisWeek"),
|
||||||
|
serverIsDownTemplate: this.loadTemplate("serverIsDown"),
|
||||||
|
serverIsUpTemplate: this.loadTemplate("serverIsUp"),
|
||||||
|
passwordResetTemplate: this.loadTemplate("passwordReset"),
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The email transporter used to send emails.
|
||||||
|
* @type {Object}
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* The email transporter used to send emails.
|
||||||
|
* @type {Object}
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { systemEmailHost, systemEmailPort, systemEmailAddress, systemEmailPassword } =
|
||||||
|
this.settingsService.getSettings();
|
||||||
|
const { systemEmailHost, systemEmailPort, systemEmailAddress, systemEmailPassword } =
|
||||||
|
this.settingsService.getSettings();
|
||||||
|
|
||||||
|
const emailConfig = {
|
||||||
|
host: systemEmailHost,
|
||||||
|
port: systemEmailPort,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: systemEmailAddress,
|
||||||
|
pass: systemEmailPassword,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const emailConfig = {
|
||||||
|
host: systemEmailHost,
|
||||||
|
port: systemEmailPort,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: systemEmailAddress,
|
||||||
|
pass: systemEmailPassword,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
this.transporter = nodemailer.createTransport(emailConfig);
|
this.transporter = nodemailer.createTransport(emailConfig);
|
||||||
}
|
}
|
||||||
|
this.transporter = this.nodemailer.createTransport(emailConfig);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Asynchronously builds and sends an email using a specified template and context.
|
* Asynchronously builds and sends an email using a specified template and context.
|
||||||
@@ -107,12 +225,33 @@ class EmailService {
|
|||||||
return info;
|
return info;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error("Error sending Email", {
|
logger.error("Error sending Email", {
|
||||||
|
>>>>>>> develop
|
||||||
error,
|
error,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
<<<<<<< HEAD
|
||||||
|
const sendEmail = async (to, subject, html) => {
|
||||||
|
try {
|
||||||
|
const info = await this.transporter.sendMail({
|
||||||
|
to: to,
|
||||||
|
subject: subject,
|
||||||
|
html: html,
|
||||||
|
});
|
||||||
|
return info;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error("Error sending Email", {
|
||||||
|
error,
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const html = await buildHtml(template, context);
|
||||||
|
const info = await sendEmail(to, subject, html);
|
||||||
|
return info?.messageId;
|
||||||
|
=======
|
||||||
try {
|
try {
|
||||||
const info = await sendEmail(to, subject, await buildHtml(template, context));
|
const info = await sendEmail(to, subject, await buildHtml(template, context));
|
||||||
return info.messageId;
|
return info.messageId;
|
||||||
@@ -126,6 +265,7 @@ class EmailService {
|
|||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
>>>>>>> develop
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
export default EmailService;
|
export default EmailService;
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import sinon from "sinon";
|
||||||
|
import EmailService from "../../service/emailService.js";
|
||||||
|
|
||||||
|
describe("EmailService - Constructor", () => {
|
||||||
|
let settingsServiceMock;
|
||||||
|
let fsMock;
|
||||||
|
let pathMock;
|
||||||
|
let compileMock;
|
||||||
|
let mjml2htmlMock;
|
||||||
|
let nodemailerMock;
|
||||||
|
let loggerMock;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
settingsServiceMock = {
|
||||||
|
getSettings: sinon.stub().returns({
|
||||||
|
systemEmailHost: "smtp.example.com",
|
||||||
|
systemEmailPort: 465,
|
||||||
|
systemEmailAddress: "test@example.com",
|
||||||
|
systemEmailPassword: "password",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
fsMock = {
|
||||||
|
readFileSync: sinon.stub().returns("<mjml><body></body></mjml>"),
|
||||||
|
};
|
||||||
|
|
||||||
|
pathMock = {
|
||||||
|
join: sinon.stub().callsFake((...args) => args.join("/")),
|
||||||
|
};
|
||||||
|
|
||||||
|
compileMock = sinon.stub().returns(() => "<mjml><body></body></mjml>");
|
||||||
|
|
||||||
|
mjml2htmlMock = sinon.stub().returns({ html: "<html></html>" });
|
||||||
|
|
||||||
|
nodemailerMock = {
|
||||||
|
createTransport: sinon.stub().returns({
|
||||||
|
sendMail: sinon.stub().resolves({ messageId: "12345" }),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
loggerMock = {
|
||||||
|
error: sinon.stub(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
sinon.restore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should initialize template loaders and email transporter", () => {
|
||||||
|
const emailService = new EmailService(
|
||||||
|
settingsServiceMock,
|
||||||
|
fsMock,
|
||||||
|
pathMock,
|
||||||
|
compileMock,
|
||||||
|
mjml2htmlMock,
|
||||||
|
nodemailerMock,
|
||||||
|
loggerMock
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify that the settingsService is assigned correctly
|
||||||
|
expect(emailService.settingsService).to.equal(settingsServiceMock);
|
||||||
|
|
||||||
|
// Verify that the template loaders are initialized
|
||||||
|
expect(emailService.templateLookup.welcomeEmailTemplate).to.be.a("function");
|
||||||
|
expect(emailService.templateLookup.employeeActivationTemplate).to.be.a("function");
|
||||||
|
|
||||||
|
// Verify that the email transporter is initialized
|
||||||
|
expect(nodemailerMock.createTransport.calledOnce).to.be.true;
|
||||||
|
const emailConfig = nodemailerMock.createTransport.getCall(0).args[0];
|
||||||
|
expect(emailConfig).to.deep.equal({
|
||||||
|
host: "smtp.example.com",
|
||||||
|
port: 465,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: "test@example.com",
|
||||||
|
pass: "password",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should have undefined templates if FS fails", () => {
|
||||||
|
fsMock = {
|
||||||
|
readFileSync: sinon.stub().throws(new Error("File read error")),
|
||||||
|
};
|
||||||
|
const emailService = new EmailService(
|
||||||
|
settingsServiceMock,
|
||||||
|
fsMock,
|
||||||
|
pathMock,
|
||||||
|
compileMock,
|
||||||
|
mjml2htmlMock,
|
||||||
|
nodemailerMock,
|
||||||
|
loggerMock
|
||||||
|
);
|
||||||
|
expect(loggerMock.error.called).to.be.true;
|
||||||
|
const errorCalls = loggerMock.error.getCalls();
|
||||||
|
const errorCall = errorCalls.find(
|
||||||
|
(call) => call.args[0] === "Error loading Email templates"
|
||||||
|
);
|
||||||
|
expect(errorCall).to.not.be.undefined;
|
||||||
|
expect(emailService.settingsService).to.equal(settingsServiceMock);
|
||||||
|
expect(emailService.templateLookup.welcomeEmailTemplate).to.be.undefined;
|
||||||
|
expect(emailService.templateLookup.employeeActivationTemplate).to.be.undefined;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("EmailService - buildAndSendEmail", () => {
|
||||||
|
let settingsServiceMock;
|
||||||
|
let fsMock;
|
||||||
|
let pathMock;
|
||||||
|
let compileMock;
|
||||||
|
let mjml2htmlMock;
|
||||||
|
let nodemailerMock;
|
||||||
|
let loggerMock;
|
||||||
|
let emailService;
|
||||||
|
beforeEach(() => {
|
||||||
|
settingsServiceMock = {
|
||||||
|
getSettings: sinon.stub().returns({
|
||||||
|
systemEmailHost: "smtp.example.com",
|
||||||
|
systemEmailPort: 465,
|
||||||
|
systemEmailAddress: "test@example.com",
|
||||||
|
systemEmailPassword: "password",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
fsMock = {
|
||||||
|
readFileSync: sinon.stub().returns("<mjml><body></body></mjml>"),
|
||||||
|
};
|
||||||
|
|
||||||
|
pathMock = {
|
||||||
|
join: sinon.stub().callsFake((...args) => args.join("/")),
|
||||||
|
};
|
||||||
|
|
||||||
|
compileMock = sinon.stub().returns(() => "<mjml><body></body></mjml>");
|
||||||
|
|
||||||
|
mjml2htmlMock = sinon.stub().returns({ html: "<html></html>" });
|
||||||
|
|
||||||
|
nodemailerMock = {
|
||||||
|
createTransport: sinon.stub().returns({
|
||||||
|
sendMail: sinon.stub().resolves({ messageId: "12345" }),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
loggerMock = {
|
||||||
|
error: sinon.stub(),
|
||||||
|
};
|
||||||
|
|
||||||
|
emailService = new EmailService(
|
||||||
|
settingsServiceMock,
|
||||||
|
fsMock,
|
||||||
|
pathMock,
|
||||||
|
compileMock,
|
||||||
|
mjml2htmlMock,
|
||||||
|
nodemailerMock,
|
||||||
|
loggerMock
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
sinon.restore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should build and send email successfully", async () => {
|
||||||
|
const messageId = await emailService.buildAndSendEmail(
|
||||||
|
"welcomeEmailTemplate",
|
||||||
|
{},
|
||||||
|
"recipient@example.com",
|
||||||
|
"Welcome"
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(messageId).to.equal("12345");
|
||||||
|
expect(nodemailerMock.createTransport().sendMail.calledOnce).to.be.true;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should log error if building HTML fails", async () => {
|
||||||
|
mjml2htmlMock.throws(new Error("MJML error"));
|
||||||
|
|
||||||
|
const messageId = await emailService.buildAndSendEmail(
|
||||||
|
"welcomeEmailTemplate",
|
||||||
|
{},
|
||||||
|
"recipient@example.com",
|
||||||
|
"Welcome"
|
||||||
|
);
|
||||||
|
expect(loggerMock.error.calledOnce).to.be.true;
|
||||||
|
expect(loggerMock.error.getCall(0).args[0]).to.equal("Error building Email HTML");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should log error if sending email fails", async () => {
|
||||||
|
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
|
||||||
|
await emailService.buildAndSendEmail(
|
||||||
|
"welcomeEmailTemplate",
|
||||||
|
{},
|
||||||
|
"recipient@example.com",
|
||||||
|
"Welcome"
|
||||||
|
);
|
||||||
|
expect(loggerMock.error.calledOnce).to.be.true;
|
||||||
|
expect(loggerMock.error.getCall(0).args[0]).to.equal("Error sending Email");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should log error if both building HTML and sending email fail", async () => {
|
||||||
|
mjml2htmlMock.throws(new Error("MJML error"));
|
||||||
|
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
|
||||||
|
|
||||||
|
const messageId = await emailService.buildAndSendEmail(
|
||||||
|
"welcomeEmailTemplate",
|
||||||
|
{},
|
||||||
|
"recipient@example.com",
|
||||||
|
"Welcome"
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(messageId).to.be.undefined;
|
||||||
|
expect(loggerMock.error.calledTwice).to.be.true;
|
||||||
|
expect(loggerMock.error.getCall(0).args[0]).to.equal("Error building Email HTML");
|
||||||
|
expect(loggerMock.error.getCall(1).args[0]).to.equal("Error sending Email");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should log an error if buildHtml fails", async () => {});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user