fix: revert tests

This commit is contained in:
cihatata authored and cihat committed 2025-02-11 07:43:39 +03:00
1 parent dea8c4fdd8
commit 08933743f1
12 files changed
+617 -645

No files matched your search

+99 -102
View File
@@ -18,16 +18,14 @@ import { getTokenFromHeaders, tokenType } from "../../utils/utils.js";
import logger from "../../utils/logger.js"; import logger from "../../utils/logger.js";
import e from "cors"; import e from "cors";
const mockLanguage = 'en'; describe("Auth Controller - issueToken", function() {
describe("Auth Controller - issueToken", function () {
let stub; let stub;
afterEach(function () { afterEach(function() {
sinon.restore(); // Restore stubs after each test sinon.restore(); // Restore stubs after each test
}); });
it("should reject with an error if jwt.sign fails", function () { it("should reject with an error if jwt.sign fails", function() {
const error = new Error("jwt.sign error"); const error = new Error("jwt.sign error");
stub = sinon.stub(jwt, "sign").throws(error); stub = sinon.stub(jwt, "sign").throws(error);
const payload = { id: "123" }; const payload = { id: "123" };
@@ -37,7 +35,7 @@ describe("Auth Controller - issueToken", function () {
); );
}); });
it("should return a token if jwt.sign is successful and appSettings.jwtTTL is not defined", function () { it("should return a token if jwt.sign is successful and appSettings.jwtTTL is not defined", function() {
const payload = { id: "123" }; const payload = { id: "123" };
const appSettings = { jwtSecret: "my_secret" }; const appSettings = { jwtSecret: "my_secret" };
const expectedToken = "mockToken"; const expectedToken = "mockToken";
@@ -47,7 +45,7 @@ describe("Auth Controller - issueToken", function () {
expect(token).to.equal(expectedToken); expect(token).to.equal(expectedToken);
}); });
it("should return a token if jwt.sign is successful and appSettings.jwtTTL is defined", function () { it("should return a token if jwt.sign is successful and appSettings.jwtTTL is defined", function() {
const payload = { id: "123" }; const payload = { id: "123" };
const appSettings = { jwtSecret: "my_secret", jwtTTL: "1s" }; const appSettings = { jwtSecret: "my_secret", jwtTTL: "1s" };
const expectedToken = "mockToken"; const expectedToken = "mockToken";
@@ -57,7 +55,7 @@ describe("Auth Controller - issueToken", function () {
expect(token).to.equal(expectedToken); expect(token).to.equal(expectedToken);
}); });
it("should return a refresh token if jwt.sign is successful and appSettings.refreshTokenTTL is not defined", function () { it("should return a refresh token if jwt.sign is successful and appSettings.refreshTokenTTL is not defined", function() {
const payload = {}; const payload = {};
const appSettings = { refreshTokenSecret: "my_refresh_secret" }; const appSettings = { refreshTokenSecret: "my_refresh_secret" };
const expectedToken = "mockRefreshToken"; const expectedToken = "mockRefreshToken";
@@ -67,7 +65,7 @@ describe("Auth Controller - issueToken", function () {
expect(token).to.equal(expectedToken); expect(token).to.equal(expectedToken);
}); });
it("should return a refresh token if jwt.sign is successful and appSettings.refreshTokenTTL is defined", function () { it("should return a refresh token if jwt.sign is successful and appSettings.refreshTokenTTL is defined", function() {
const payload = {}; const payload = {};
const appSettings = { const appSettings = {
refreshTokenSecret: "my_refresh_secret", refreshTokenSecret: "my_refresh_secret",
@@ -81,10 +79,10 @@ describe("Auth Controller - issueToken", function () {
}); });
}); });
describe("Auth Controller - registerUser", function () { describe("Auth Controller - registerUser", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: { body: {
firstName: "firstname", firstName: "firstname",
@@ -120,25 +118,25 @@ describe("Auth Controller - registerUser", function () {
sinon.stub(logger, "error"); sinon.stub(logger, "error");
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if body validation fails", async function () { it("should reject with an error if body validation fails", async function() {
req.body = {}; req.body = {};
await registerUser(req, res, next); await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if checkSuperadmin fails", async function () { it("should reject with an error if checkSuperadmin fails", async function() {
req.db.checkSuperadmin.throws(new Error("checkSuperadmin error")); req.db.checkSuperadmin.throws(new Error("checkSuperadmin error"));
await registerUser(req, res, next); await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error"); expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error");
}); });
it("should reject with an error if getInviteTokenAndDelete fails", async function () { it("should reject with an error if getInviteTokenAndDelete fails", async function() {
req.db.checkSuperadmin.returns(true); req.db.checkSuperadmin.returns(true);
req.db.getInviteTokenAndDelete.throws(new Error("getInviteTokenAndDelete error")); req.db.getInviteTokenAndDelete.throws(new Error("getInviteTokenAndDelete error"));
await registerUser(req, res, next); await registerUser(req, res, next);
@@ -146,7 +144,7 @@ describe("Auth Controller - registerUser", function () {
expect(next.firstCall.args[0].message).to.equal("getInviteTokenAndDelete error"); expect(next.firstCall.args[0].message).to.equal("getInviteTokenAndDelete error");
}); });
it("should reject with an error if updateAppSettings fails", async function () { it("should reject with an error if updateAppSettings fails", async function() {
req.db.checkSuperadmin.returns(false); req.db.checkSuperadmin.returns(false);
req.db.updateAppSettings.throws(new Error("updateAppSettings error")); req.db.updateAppSettings.throws(new Error("updateAppSettings error"));
await registerUser(req, res, next); await registerUser(req, res, next);
@@ -154,7 +152,7 @@ describe("Auth Controller - registerUser", function () {
expect(next.firstCall.args[0].message).to.equal("updateAppSettings error"); expect(next.firstCall.args[0].message).to.equal("updateAppSettings error");
}); });
it("should reject with an error if insertUser fails", async function () { it("should reject with an error if insertUser fails", async function() {
req.db.checkSuperadmin.resolves(false); req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves(); req.db.updateAppSettings.resolves();
req.db.insertUser.rejects(new Error("insertUser error")); req.db.insertUser.rejects(new Error("insertUser error"));
@@ -163,7 +161,7 @@ describe("Auth Controller - registerUser", function () {
expect(next.firstCall.args[0].message).to.equal("insertUser error"); expect(next.firstCall.args[0].message).to.equal("insertUser error");
}); });
it("should reject with an error if settingsService.getSettings fails", async function () { it("should reject with an error if settingsService.getSettings fails", async function() {
req.db.checkSuperadmin.resolves(false); req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves(); req.db.updateAppSettings.resolves();
req.db.insertUser.resolves({ _id: "123" }); req.db.insertUser.resolves({ _id: "123" });
@@ -175,7 +173,7 @@ describe("Auth Controller - registerUser", function () {
expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error"); expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error");
}); });
it("should log an error if emailService.buildAndSendEmail fails", async function () { it("should log an error if emailService.buildAndSendEmail fails", async function() {
req.db.checkSuperadmin.resolves(false); req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves(); req.db.updateAppSettings.resolves();
req.db.insertUser.returns({ _id: "123" }); req.db.insertUser.returns({ _id: "123" });
@@ -189,7 +187,7 @@ describe("Auth Controller - registerUser", function () {
expect(logger.error.firstCall.args[0].message).to.equal("emailService error"); expect(logger.error.firstCall.args[0].message).to.equal("emailService error");
}); });
it("should return a success message and data if all operations are successful", async function () { it("should return a success message and data if all operations are successful", async function() {
const user = { _id: "123" }; const user = { _id: "123" };
req.db.checkSuperadmin.resolves(false); req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves(); req.db.updateAppSettings.resolves();
@@ -204,14 +202,14 @@ describe("Auth Controller - registerUser", function () {
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.AUTH_CREATE_USER(mockLanguage), msg: successMessages.AUTH_CREATE_USER,
data: { user, token: sinon.match.string, refreshToken: sinon.match.string }, data: { user, token: sinon.match.string, refreshToken: sinon.match.string },
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should return a success message and data if all operations are successful and superAdmin true", async function () { it("should return a success message and data if all operations are successful and superAdmin true", async function() {
const user = { _id: "123" }; const user = { _id: "123" };
req.db.checkSuperadmin.resolves(true); req.db.checkSuperadmin.resolves(true);
req.db.updateAppSettings.resolves(); req.db.updateAppSettings.resolves();
@@ -226,7 +224,7 @@ describe("Auth Controller - registerUser", function () {
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.AUTH_CREATE_USER(mockLanguage), msg: successMessages.AUTH_CREATE_USER,
data: { user, token: sinon.match.string, refreshToken: sinon.match.string }, data: { user, token: sinon.match.string, refreshToken: sinon.match.string },
}) })
).to.be.true; ).to.be.true;
@@ -234,16 +232,15 @@ describe("Auth Controller - registerUser", function () {
}); });
}); });
describe("Auth Controller - loginUser", function () { describe("Auth Controller - loginUser", function() {
let req, res, next, user; let req, res, next, user;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: { email: "test@example.com", password: "Password123!" }, body: { email: "test@example.com", password: "Password123!" },
db: { db: {
getUserByEmail: sinon.stub(), getUserByEmail: sinon.stub(),
}, },
language: 'en',
settingsService: { settingsService: {
getSettings: sinon.stub().resolves({ getSettings: sinon.stub().resolves({
jwtSecret: "my_secret", jwtSecret: "my_secret",
@@ -264,21 +261,21 @@ describe("Auth Controller - loginUser", function () {
}; };
}); });
it("should reject with an error if validation fails", async function () { it("should reject with an error if validation fails", async function() {
req.body = {}; req.body = {};
await loginUser(req, res, next); await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if getUserByEmail fails", async function () { it("should reject with an error if getUserByEmail fails", async function() {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error")); req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await loginUser(req, res, next); await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error"); expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
}); });
it("should login user successfully", async function () { it("should login user successfully", async function() {
req.db.getUserByEmail.resolves(user); req.db.getUserByEmail.resolves(user);
user.comparePassword.resolves(true); user.comparePassword.resolves(true);
await loginUser(req, res, next); await loginUser(req, res, next);
@@ -286,7 +283,7 @@ describe("Auth Controller - loginUser", function () {
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.AUTH_LOGIN_USER(mockLanguage), msg: successMessages.AUTH_LOGIN_USER,
data: { data: {
user: { user: {
email: "test@example.com", email: "test@example.com",
@@ -300,7 +297,7 @@ describe("Auth Controller - loginUser", function () {
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should reject a user with an incorrect password", async function () { it("should reject a user with an incorrect password", async function() {
req.body = { req.body = {
email: "test@test.com", email: "test@test.com",
password: "Password123!", password: "Password123!",
@@ -310,15 +307,15 @@ describe("Auth Controller - loginUser", function () {
await loginUser(req, res, next); await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal( expect(next.firstCall.args[0].message).to.equal(
errorMessages.AUTH_INCORRECT_PASSWORD(mockLanguage) errorMessages.AUTH_INCORRECT_PASSWORD
); );
}); });
}); });
describe("Auth Controller - refreshAuthToken", function () { describe("Auth Controller - refreshAuthToken", function() {
let req, res, next, issueTokenStub; let req, res, next, issueTokenStub;
beforeEach(function () { beforeEach(function() {
req = { req = {
headers: { headers: {
"x-refresh-token": "valid_refresh_token", "x-refresh-token": "valid_refresh_token",
@@ -342,39 +339,39 @@ describe("Auth Controller - refreshAuthToken", function () {
sinon.replace({ issueToken }, "issueToken", issueTokenStub); sinon.replace({ issueToken }, "issueToken", issueTokenStub);
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject if no refresh token is provided", async function () { it("should reject if no refresh token is provided", async function() {
delete req.headers["x-refresh-token"]; delete req.headers["x-refresh-token"];
await refreshAuthToken(req, res, next); await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.NO_REFRESH_TOKEN(req.language)); expect(next.firstCall.args[0].message).to.equal(errorMessages.NO_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401); expect(next.firstCall.args[0].status).to.equal(401);
}); });
it("should reject if the refresh token is invalid", async function () { it("should reject if the refresh token is invalid", async function() {
jwt.verify.yields(new Error("invalid token")); jwt.verify.yields(new Error("invalid token"));
await refreshAuthToken(req, res, next); await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.INVALID_REFRESH_TOKEN(req.language)); expect(next.firstCall.args[0].message).to.equal(errorMessages.INVALID_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401); expect(next.firstCall.args[0].status).to.equal(401);
}); });
it("should reject if the refresh token is expired", async function () { it("should reject if the refresh token is expired", async function() {
const error = new Error("Token expired"); const error = new Error("Token expired");
error.name = "TokenExpiredError"; error.name = "TokenExpiredError";
jwt.verify.yields(error); jwt.verify.yields(error);
await refreshAuthToken(req, res, next); await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.EXPIRED_REFRESH_TOKEN(req.language)); expect(next.firstCall.args[0].message).to.equal(errorMessages.EXPIRED_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401); expect(next.firstCall.args[0].status).to.equal(401);
}); });
it("should reject if settingsService.getSettings fails", async function () { it("should reject if settingsService.getSettings fails", async function() {
req.settingsService.getSettings.rejects( req.settingsService.getSettings.rejects(
new Error("settingsService.getSettings error") new Error("settingsService.getSettings error")
); );
@@ -384,7 +381,7 @@ describe("Auth Controller - refreshAuthToken", function () {
expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error"); expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error");
}); });
it("should generate a new auth token if the refresh token is valid", async function () { it("should generate a new auth token if the refresh token is valid", async function() {
const decodedPayload = { expiresIn: "60" }; const decodedPayload = { expiresIn: "60" };
jwt.verify.callsFake(() => { jwt.verify.callsFake(() => {
return decodedPayload; return decodedPayload;
@@ -395,7 +392,7 @@ describe("Auth Controller - refreshAuthToken", function () {
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.AUTH_TOKEN_REFRESHED(mockLanguage), msg: successMessages.AUTH_TOKEN_REFRESHED,
data: { data: {
user: decodedPayload, user: decodedPayload,
token: sinon.match.string, token: sinon.match.string,
@@ -406,10 +403,10 @@ describe("Auth Controller - refreshAuthToken", function () {
}); });
}); });
describe("Auth Controller - editUser", function () { describe("Auth Controller - editUser", function() {
let req, res, next, stub, user; let req, res, next, stub, user;
beforeEach(function () { beforeEach(function() {
req = { req = {
params: { userId: "123" }, params: { userId: "123" },
body: { password: "Password1!", newPassword: "Password2!" }, body: { password: "Password1!", newPassword: "Password2!" },
@@ -431,40 +428,40 @@ describe("Auth Controller - editUser", function () {
stub = sinon.stub(jwt, "verify").returns({ email: "test@example.com" }); stub = sinon.stub(jwt, "verify").returns({ email: "test@example.com" });
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
stub.restore(); stub.restore();
}); });
it("should reject with an error if param validation fails", async function () { it("should reject with an error if param validation fails", async function() {
req.params = {}; req.params = {};
await editUser(req, res, next); await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if body validation fails", async function () { it("should reject with an error if body validation fails", async function() {
req.body = { invalid: 1 }; req.body = { invalid: 1 };
await editUser(req, res, next); await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if param.userId !== req.user._id", async function () { it("should reject with an error if param.userId !== req.user._id", async function() {
req.params = { userId: "456" }; req.params = { userId: "456" };
await editUser(req, res, next); await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(401); expect(next.firstCall.args[0].status).to.equal(401);
}); });
it("should reject with an error if !req.body.password and getUserByEmail fails", async function () { it("should reject with an error if !req.body.password and getUserByEmail fails", async function() {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error")); req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await editUser(req, res, next); await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error"); expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
}); });
it("should reject with an error if user.comparePassword fails", async function () { it("should reject with an error if user.comparePassword fails", async function() {
req.db.getUserByEmail.returns({ req.db.getUserByEmail.returns({
comparePassword: sinon.stub().rejects(new Error("Bad Password Match")), comparePassword: sinon.stub().rejects(new Error("Bad Password Match")),
}); });
@@ -473,7 +470,7 @@ describe("Auth Controller - editUser", function () {
expect(next.firstCall.args[0].message).to.equal("Bad Password Match"); expect(next.firstCall.args[0].message).to.equal("Bad Password Match");
}); });
it("should reject with an error if user.comparePassword returns false", async function () { it("should reject with an error if user.comparePassword returns false", async function() {
req.db.getUserByEmail.returns({ req.db.getUserByEmail.returns({
comparePassword: sinon.stub().returns(false), comparePassword: sinon.stub().returns(false),
}); });
@@ -481,11 +478,11 @@ describe("Auth Controller - editUser", function () {
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(401); expect(next.firstCall.args[0].status).to.equal(401);
expect(next.firstCall.args[0].message).to.equal( expect(next.firstCall.args[0].message).to.equal(
errorMessages.AUTH_INCORRECT_PASSWORD(mockLanguage) errorMessages.AUTH_INCORRECT_PASSWORD
); );
}); });
it("should edit a user if it receives a proper request", async function () { it("should edit a user if it receives a proper request", async function() {
const user = { const user = {
comparePassword: sinon.stub().resolves(true), comparePassword: sinon.stub().resolves(true),
}; };
@@ -500,14 +497,14 @@ describe("Auth Controller - editUser", function () {
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.AUTH_UPDATE_USER(mockLanguage), msg: successMessages.AUTH_UPDATE_USER,
data: { email: "test@example.com" }, data: { email: "test@example.com" },
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should edit a user if it receives a proper request and both password fields are undefined", async function () { it("should edit a user if it receives a proper request and both password fields are undefined", async function() {
req.body.password = undefined; req.body.password = undefined;
req.body.newPassword = undefined; req.body.newPassword = undefined;
req.db.getUserByEmail.resolves(user); req.db.getUserByEmail.resolves(user);
@@ -518,14 +515,14 @@ describe("Auth Controller - editUser", function () {
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.AUTH_UPDATE_USER(mockLanguage), msg: successMessages.AUTH_UPDATE_USER,
data: { email: "test@example.com" }, data: { email: "test@example.com" },
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should reject an edit request if password format is incorrect", async function () { it("should reject an edit request if password format is incorrect", async function() {
req.body = { password: "bad_password", newPassword: "bad_password" }; req.body = { password: "bad_password", newPassword: "bad_password" };
const user = { const user = {
comparePassword: sinon.stub().resolves(true), comparePassword: sinon.stub().resolves(true),
@@ -539,10 +536,10 @@ describe("Auth Controller - editUser", function () {
}); });
}); });
describe("Auth Controller - checkSuperadminExists", function () { describe("Auth Controller - checkSuperadminExists", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
db: { db: {
checkSuperadmin: sinon.stub(), checkSuperadmin: sinon.stub(),
@@ -555,35 +552,35 @@ describe("Auth Controller - checkSuperadminExists", function () {
next = sinon.stub(); next = sinon.stub();
}); });
it("should reject with an error if checkSuperadmin fails", async function () { it("should reject with an error if checkSuperadmin fails", async function() {
req.db.checkSuperadmin.rejects(new Error("checkSuperadmin error")); req.db.checkSuperadmin.rejects(new Error("checkSuperadmin error"));
await checkSuperadminExists(req, res, next); await checkSuperadminExists(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error"); expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error");
}); });
it("should return true if a superadmin exists", async function () { it("should return true if a superadmin exists", async function() {
req.db.checkSuperadmin.resolves(true); req.db.checkSuperadmin.resolves(true);
await checkSuperadminExists(req, res, next); await checkSuperadminExists(req, res, next);
expect(res.status.calledWith(200)).to.be.true; expect(res.status.calledWith(200)).to.be.true;
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.AUTH_SUPERADMIN_EXISTS(mockLanguage), msg: successMessages.AUTH_SUPERADMIN_EXISTS,
data: true, data: true,
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should return false if a superadmin does not exist", async function () { it("should return false if a superadmin does not exist", async function() {
req.db.checkSuperadmin.resolves(false); req.db.checkSuperadmin.resolves(false);
await checkSuperadminExists(req, res, next); await checkSuperadminExists(req, res, next);
expect(res.status.calledWith(200)).to.be.true; expect(res.status.calledWith(200)).to.be.true;
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.AUTH_SUPERADMIN_EXISTS(mockLanguage), msg: successMessages.AUTH_SUPERADMIN_EXISTS,
data: false, data: false,
}) })
).to.be.true; ).to.be.true;
@@ -591,10 +588,10 @@ describe("Auth Controller - checkSuperadminExists", function () {
}); });
}); });
describe("Auth Controller - requestRecovery", function () { describe("Auth Controller - requestRecovery", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: { email: "test@test.com" }, body: { email: "test@test.com" },
db: { db: {
@@ -615,21 +612,21 @@ describe("Auth Controller - requestRecovery", function () {
next = sinon.stub(); next = sinon.stub();
}); });
it("should reject with an error if validation fails", async function () { it("should reject with an error if validation fails", async function() {
req.body = {}; req.body = {};
await requestRecovery(req, res, next); await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if getUserByEmail fails", async function () { it("should reject with an error if getUserByEmail fails", async function() {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error")); req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await requestRecovery(req, res, next); await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error"); expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
}); });
it("should throw an error if the user is not found", async function () { it("should throw an error if the user is not found", async function() {
req.db.getUserByEmail.resolves(null); req.db.getUserByEmail.resolves(null);
await requestRecovery(req, res, next); await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
@@ -638,14 +635,14 @@ describe("Auth Controller - requestRecovery", function () {
// ); // );
}); });
it("should throw an error if the email is not provided", async function () { it("should throw an error if the email is not provided", async function() {
req.body = {}; req.body = {};
await requestRecovery(req, res, next); await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should return a success message if the email is provided", async function () { it("should return a success message if the email is provided", async function() {
const user = { firstName: "John" }; const user = { firstName: "John" };
const recoveryToken = { token: "recovery-token" }; const recoveryToken = { token: "recovery-token" };
const msgId = "message-id"; const msgId = "message-id";
@@ -671,7 +668,7 @@ describe("Auth Controller - requestRecovery", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN(mockLanguage), msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
data: msgId, data: msgId,
}) })
).to.be.true; ).to.be.true;
@@ -679,10 +676,10 @@ describe("Auth Controller - requestRecovery", function () {
}); });
}); });
describe("Auth Controller - validateRecovery", function () { describe("Auth Controller - validateRecovery", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: { recoveryToken: "recovery-token" }, body: { recoveryToken: "recovery-token" },
db: { db: {
@@ -696,38 +693,38 @@ describe("Auth Controller - validateRecovery", function () {
next = sinon.stub(); next = sinon.stub();
}); });
it("should reject with an error if validation fails", async function () { it("should reject with an error if validation fails", async function() {
req.body = {}; req.body = {};
await validateRecovery(req, res, next); await validateRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if validateRecoveryToken fails", async function () { it("should reject with an error if validateRecoveryToken fails", async function() {
req.db.validateRecoveryToken.rejects(new Error("validateRecoveryToken error")); req.db.validateRecoveryToken.rejects(new Error("validateRecoveryToken error"));
await validateRecovery(req, res, next); await validateRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("validateRecoveryToken error"); expect(next.firstCall.args[0].message).to.equal("validateRecoveryToken error");
}); });
it("should return a success message if the token is valid", async function () { it("should return a success message if the token is valid", async function() {
req.db.validateRecoveryToken.resolves(); req.db.validateRecoveryToken.resolves();
await validateRecovery(req, res, next); await validateRecovery(req, res, next);
expect(res.status.calledOnceWith(200)).to.be.true; expect(res.status.calledOnceWith(200)).to.be.true;
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN(mockLanguage), msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
}); });
describe("Auth Controller - resetPassword", function () { describe("Auth Controller - resetPassword", function() {
let req, res, next, newPasswordValidation, handleValidationError, handleError; let req, res, next, newPasswordValidation, handleValidationError, handleError;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: { body: {
recoveryToken: "recovery-token", recoveryToken: "recovery-token",
@@ -752,14 +749,14 @@ describe("Auth Controller - resetPassword", function () {
handleError = sinon.stub(); handleError = sinon.stub();
}); });
it("should reject with an error if validation fails", async function () { it("should reject with an error if validation fails", async function() {
req.body = { password: "bad_password" }; req.body = { password: "bad_password" };
await resetPassword(req, res, next); await resetPassword(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if resetPassword fails", async function () { it("should reject with an error if resetPassword fails", async function() {
const error = new Error("resetPassword error"); const error = new Error("resetPassword error");
newPasswordValidation.validateAsync.resolves(); newPasswordValidation.validateAsync.resolves();
req.db.resetPassword.rejects(error); req.db.resetPassword.rejects(error);
@@ -768,7 +765,7 @@ describe("Auth Controller - resetPassword", function () {
expect(next.firstCall.args[0].message).to.equal("resetPassword error"); expect(next.firstCall.args[0].message).to.equal("resetPassword error");
}); });
it("should reset password successfully", async function () { it("should reset password successfully", async function() {
const user = { _doc: {} }; const user = { _doc: {} };
const appSettings = { jwtSecret: "my_secret" }; const appSettings = { jwtSecret: "my_secret" };
const token = "token"; const token = "token";
@@ -785,7 +782,7 @@ describe("Auth Controller - resetPassword", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.AUTH_RESET_PASSWORD(mockLanguage), msg: successMessages.AUTH_RESET_PASSWORD,
data: { user: sinon.match.object, token: sinon.match.string }, data: { user: sinon.match.object, token: sinon.match.string },
}) })
).to.be.true; ).to.be.true;
@@ -793,10 +790,10 @@ describe("Auth Controller - resetPassword", function () {
}); });
}); });
describe("Auth Controller - deleteUser", function () { describe("Auth Controller - deleteUser", function() {
let req, res, next, handleError; let req, res, next, handleError;
beforeEach(function () { beforeEach(function() {
req = { req = {
headers: { headers: {
authorization: "Bearer token", authorization: "Bearer token",
@@ -828,24 +825,24 @@ describe("Auth Controller - deleteUser", function () {
handleError = sinon.stub(); handleError = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should throw an error if user is not found", async function () { it("should throw an error if user is not found", async function() {
jwt.decode.returns({ email: "test@example.com" }); jwt.decode.returns({ email: "test@example.com" });
req.db.getUserByEmail.throws(new Error(errorMessages.DB_USER_NOT_FOUND(req.language))); req.db.getUserByEmail.throws(new Error(errorMessages.DB_USER_NOT_FOUND));
await deleteUser(req, res, next); await deleteUser(req, res, next);
expect(req.db.getUserByEmail.calledOnceWith("test@example.com")).to.be.true; expect(req.db.getUserByEmail.calledOnceWith("test@example.com")).to.be.true;
expect(next.calledOnce).to.be.true; expect(next.calledOnce).to.be.true;
expect(next.firstCall.args[0].message).to.equal(errorMessages.DB_USER_NOT_FOUND(req.language)); expect(next.firstCall.args[0].message).to.equal(errorMessages.DB_USER_NOT_FOUND);
expect(res.status.notCalled).to.be.true; expect(res.status.notCalled).to.be.true;
expect(res.json.notCalled).to.be.true; expect(res.json.notCalled).to.be.true;
}); });
it("should delete user and associated data if user is superadmin", async function () { it("should delete user and associated data if user is superadmin", async function() {
const user = { const user = {
_id: "user_id", _id: "user_id",
email: "test@example.com", email: "test@example.com",
@@ -879,13 +876,13 @@ describe("Auth Controller - deleteUser", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.AUTH_DELETE_USER(mockLanguage), msg: successMessages.AUTH_DELETE_USER,
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should delete user if user is not superadmin", async function () { it("should delete user if user is not superadmin", async function() {
const user = { const user = {
_id: "user_id", _id: "user_id",
email: "test@example.com", email: "test@example.com",
@@ -909,13 +906,13 @@ describe("Auth Controller - deleteUser", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.AUTH_DELETE_USER(mockLanguage), msg: successMessages.AUTH_DELETE_USER,
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should handle errors", async function () { it("should handle errors", async function() {
const error = new Error("Something went wrong"); const error = new Error("Something went wrong");
const SERVICE_NAME = "AuthController"; const SERVICE_NAME = "AuthController";
jwt.decode.returns({ email: "test@example.com" }); jwt.decode.returns({ email: "test@example.com" });
@@ -928,10 +925,10 @@ describe("Auth Controller - deleteUser", function () {
}); });
}); });
describe("Auth Controller - getAllUsers", function () { describe("Auth Controller - getAllUsers", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
db: { db: {
getAllUsers: sinon.stub(), getAllUsers: sinon.stub(),
@@ -944,11 +941,11 @@ describe("Auth Controller - getAllUsers", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); // Restore the original methods after each test sinon.restore(); // Restore the original methods after each test
}); });
it("should return 200 and all users", async function () { it("should return 200 and all users", async function() {
const allUsers = [{ id: 1, name: "John Doe" }]; const allUsers = [{ id: 1, name: "John Doe" }];
req.db.getAllUsers.resolves(allUsers); req.db.getAllUsers.resolves(allUsers);
@@ -966,7 +963,7 @@ describe("Auth Controller - getAllUsers", function () {
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should call next with error when an exception occurs", async function () { it("should call next with error when an exception occurs", async function() {
const error = new Error("Something went wrong"); const error = new Error("Something went wrong");
req.db.getAllUsers.rejects(error); req.db.getAllUsers.rejects(error);
await getAllUsers(req, res, next); await getAllUsers(req, res, next);
@@ -9,12 +9,11 @@ import {
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { errorMessages, successMessages } from "../../utils/messages.js"; import { errorMessages, successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
describe("Check Controller - createCheck", function () { describe("Check Controller - createCheck", function() {
let req, res, next, handleError; let req, res, next, handleError;
beforeEach(function () { beforeEach(function() {
req = { req = {
language: 'en',
params: {}, params: {},
body: {}, body: {},
db: { db: {
@@ -29,17 +28,17 @@ describe("Check Controller - createCheck", function () {
handleError = sinon.stub(); handleError = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); // Restore the original methods after each test sinon.restore(); // Restore the original methods after each test
}); });
it("should reject with a validation if params are invalid", async function () { it("should reject with a validation if params are invalid", async function() {
await createCheck(req, res, next); await createCheck(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with a validation error if body is invalid", async function () { it("should reject with a validation error if body is invalid", async function() {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
@@ -48,7 +47,7 @@ describe("Check Controller - createCheck", function () {
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should call next with error if data retrieval fails", async function () { it("should call next with error if data retrieval fails", async function() {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
@@ -64,7 +63,7 @@ describe("Check Controller - createCheck", function () {
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
}); });
it("should return a success message if check is created", async function () { it("should return a success message if check is created", async function() {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
@@ -81,7 +80,7 @@ describe("Check Controller - createCheck", function () {
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.CHECK_CREATE(req.language), msg: successMessages.CHECK_CREATE,
data: { id: "123" }, data: { id: "123" },
}) })
).to.be.true; ).to.be.true;
@@ -89,10 +88,10 @@ describe("Check Controller - createCheck", function () {
}); });
}); });
describe("Check Controller - getChecks", function () { describe("Check Controller - getChecks", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
params: {}, params: {},
query: {}, query: {},
@@ -108,17 +107,17 @@ describe("Check Controller - getChecks", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject with a validation error if params are invalid", async function () { it("should reject with a validation error if params are invalid", async function() {
await getChecks(req, res, next); await getChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should return a success message if checks are found", async function () { it("should return a success message if checks are found", async function() {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
@@ -129,14 +128,14 @@ describe("Check Controller - getChecks", function () {
expect( expect(
res.json.calledWith({ res.json.calledWith({
success: true, success: true,
msg: successMessages.CHECK_GET(req.language), msg: successMessages.CHECK_GET,
data: { checksCount: 1, checks: [{ id: "123" }] }, data: { checksCount: 1, checks: [{ id: "123" }] },
}) })
).to.be.true; ).to.be.true;
expect(next.notCalled).to.be.true; expect(next.notCalled).to.be.true;
}); });
it("should call next with error if data retrieval fails", async function () { it("should call next with error if data retrieval fails", async function() {
req.params = { req.params = {
monitorId: "monitorId", monitorId: "monitorId",
}; };
@@ -146,10 +145,10 @@ describe("Check Controller - getChecks", function () {
}); });
}); });
describe("Check Controller - getTeamChecks", function () { describe("Check Controller - getTeamChecks", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
params: {}, params: {},
query: {}, query: {},
@@ -164,17 +163,17 @@ describe("Check Controller - getTeamChecks", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject with a validation error if params are invalid", async function () { it("should reject with a validation error if params are invalid", async function() {
await getTeamChecks(req, res, next); await getTeamChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should return 200 and check data on successful validation and data retrieval", async function () { it("should return 200 and check data on successful validation and data retrieval", async function() {
req.params = { teamId: "1" }; req.params = { teamId: "1" };
const checkData = [{ id: 1, name: "Check 1" }]; const checkData = [{ id: 1, name: "Check 1" }];
req.db.getTeamChecks.resolves(checkData); req.db.getTeamChecks.resolves(checkData);
@@ -185,13 +184,13 @@ describe("Check Controller - getTeamChecks", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.CHECK_GET(req.language), msg: successMessages.CHECK_GET,
data: checkData, data: checkData,
}) })
).to.be.true; ).to.be.true;
}); });
it("should call next with error if data retrieval fails", async function () { it("should call next with error if data retrieval fails", async function() {
req.params = { teamId: "1" }; req.params = { teamId: "1" };
req.db.getTeamChecks.rejects(new Error("Retrieval Error")); req.db.getTeamChecks.rejects(new Error("Retrieval Error"));
await getTeamChecks(req, res, next); await getTeamChecks(req, res, next);
@@ -202,10 +201,10 @@ describe("Check Controller - getTeamChecks", function () {
}); });
}); });
describe("Check Controller - deleteChecks", function () { describe("Check Controller - deleteChecks", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
params: {}, params: {},
db: { db: {
@@ -219,17 +218,17 @@ describe("Check Controller - deleteChecks", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if param validation fails", async function () { it("should reject with an error if param validation fails", async function() {
await deleteChecks(req, res, next); await deleteChecks(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should call next with error if data retrieval fails", async function () { it("should call next with error if data retrieval fails", async function() {
req.params = { monitorId: "1" }; req.params = { monitorId: "1" };
req.db.deleteChecks.rejects(new Error("Deletion Error")); req.db.deleteChecks.rejects(new Error("Deletion Error"));
await deleteChecks(req, res, next); await deleteChecks(req, res, next);
@@ -239,7 +238,7 @@ describe("Check Controller - deleteChecks", function () {
expect(res.json.notCalled).to.be.true; expect(res.json.notCalled).to.be.true;
}); });
it("should delete checks successfully", async function () { it("should delete checks successfully", async function() {
req.params = { monitorId: "123" }; req.params = { monitorId: "123" };
req.db.deleteChecks.resolves(1); req.db.deleteChecks.resolves(1);
await deleteChecks(req, res, next); await deleteChecks(req, res, next);
@@ -248,17 +247,17 @@ describe("Check Controller - deleteChecks", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.CHECK_DELETE(req.language), msg: successMessages.CHECK_DELETE,
data: { deletedCount: 1 }, data: { deletedCount: 1 },
}) })
).to.be.true; ).to.be.true;
}); });
}); });
describe("Check Controller - deleteChecksByTeamId", function () { describe("Check Controller - deleteChecksByTeamId", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
params: {}, params: {},
db: { db: {
@@ -272,17 +271,17 @@ describe("Check Controller - deleteChecksByTeamId", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if param validation fails", async function () { it("should reject with an error if param validation fails", async function() {
await deleteChecksByTeamId(req, res, next); await deleteChecksByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should call next with error if data retrieval fails", async function () { it("should call next with error if data retrieval fails", async function() {
req.params = { teamId: "1" }; req.params = { teamId: "1" };
req.db.deleteChecksByTeamId.rejects(new Error("Deletion Error")); req.db.deleteChecksByTeamId.rejects(new Error("Deletion Error"));
await deleteChecksByTeamId(req, res, next); await deleteChecksByTeamId(req, res, next);
@@ -292,7 +291,7 @@ describe("Check Controller - deleteChecksByTeamId", function () {
expect(res.json.notCalled).to.be.true; expect(res.json.notCalled).to.be.true;
}); });
it("should delete checks successfully", async function () { it("should delete checks successfully", async function() {
req.params = { teamId: "123" }; req.params = { teamId: "123" };
req.db.deleteChecksByTeamId.resolves(1); req.db.deleteChecksByTeamId.resolves(1);
await deleteChecksByTeamId(req, res, next); await deleteChecksByTeamId(req, res, next);
@@ -301,17 +300,17 @@ describe("Check Controller - deleteChecksByTeamId", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.CHECK_DELETE(req.language), msg: successMessages.CHECK_DELETE,
data: { deletedCount: 1 }, data: { deletedCount: 1 },
}) })
).to.be.true; ).to.be.true;
}); });
}); });
describe("Check Controller - updateCheckTTL", function () { describe("Check Controller - updateCheckTTL", function() {
let stub, req, res, next; let stub, req, res, next;
beforeEach(function () { beforeEach(function() {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
@@ -333,18 +332,18 @@ describe("Check Controller - updateCheckTTL", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
stub.restore(); stub.restore();
}); });
it("should reject if body validation fails", async function () { it("should reject if body validation fails", async function() {
await updateChecksTTL(req, res, next); await updateChecksTTL(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should throw a JwtError if verification fails", async function () { it("should throw a JwtError if verification fails", async function() {
stub.restore(); stub.restore();
req.body = { req.body = {
ttl: 1, ttl: 1,
@@ -353,7 +352,7 @@ describe("Check Controller - updateCheckTTL", function () {
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
}); });
it("should call next with error if data retrieval fails", async function () { it("should call next with error if data retrieval fails", async function() {
req.body = { req.body = {
ttl: 1, ttl: 1,
}; };
@@ -362,7 +361,7 @@ describe("Check Controller - updateCheckTTL", function () {
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
}); });
it("should update TTL successfully", async function () { it("should update TTL successfully", async function() {
req.body = { req.body = {
ttl: 1, ttl: 1,
}; };
@@ -373,7 +372,7 @@ describe("Check Controller - updateCheckTTL", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.CHECK_UPDATE_TTL(req.language), msg: successMessages.CHECK_UPDATE_TTL,
}) })
).to.be.true; ).to.be.true;
}); });
@@ -11,12 +11,11 @@ import jwt from "jsonwebtoken";
import { successMessages } from "../../utils/messages.js"; import { successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
describe("maintenanceWindowController - createMaintenanceWindows", function () { describe("maintenanceWindowController - createMaintenanceWindows", function() {
let req, res, next, stub; let req, res, next, stub;
beforeEach(function () { beforeEach(function() {
req = { req = {
language: 'en',
body: { body: {
monitors: ["66ff52e7c5911c61698ac724"], monitors: ["66ff52e7c5911c61698ac724"],
name: "window", name: "window",
@@ -42,11 +41,11 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if body validation fails", async function () { it("should reject with an error if body validation fails", async function() {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
@@ -57,14 +56,14 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
stub.restore(); stub.restore();
}); });
it("should reject with an error if jwt.verify fails", async function () { it("should reject with an error if jwt.verify fails", async function() {
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError()); stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
await createMaintenanceWindows(req, res, next); await createMaintenanceWindows(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
stub.restore(); stub.restore();
}); });
it("should reject with an error DB operations fail", async function () { it("should reject with an error DB operations fail", async function() {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
@@ -75,7 +74,7 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
stub.restore(); stub.restore();
}); });
it("should return success message if all operations are successful", async function () { it("should return success message if all operations are successful", async function() {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
@@ -84,13 +83,13 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_CREATE(req.language), msg: successMessages.MAINTENANCE_WINDOW_CREATE,
}) })
).to.be.true; ).to.be.true;
stub.restore(); stub.restore();
}); });
it("should return success message if all operations are successful with active set to undefined", async function () { it("should return success message if all operations are successful with active set to undefined", async function() {
req.body.active = undefined; req.body.active = undefined;
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
@@ -100,17 +99,17 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_CREATE(req.language), msg: successMessages.MAINTENANCE_WINDOW_CREATE,
}) })
).to.be.true; ).to.be.true;
stub.restore(); stub.restore();
}); });
}); });
describe("maintenanceWindowController - getMaintenanceWindowById", function () { describe("maintenanceWindowController - getMaintenanceWindowById", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: {}, body: {},
params: { params: {
@@ -122,7 +121,6 @@ describe("maintenanceWindowController - getMaintenanceWindowById", function () {
settingsService: { settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }), getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
}, },
language: 'en',
db: { db: {
getMaintenanceWindowById: sinon.stub(), getMaintenanceWindowById: sinon.stub(),
}, },
@@ -134,38 +132,38 @@ describe("maintenanceWindowController - getMaintenanceWindowById", function () {
next = sinon.stub(); next = sinon.stub();
}); });
it("should reject if param validation fails", async function () { it("should reject if param validation fails", async function() {
req.params = {}; req.params = {};
await getMaintenanceWindowById(req, res, next); await getMaintenanceWindowById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject if DB operations fail", async function () { it("should reject if DB operations fail", async function() {
req.db.getMaintenanceWindowById.throws(new Error("DB error")); req.db.getMaintenanceWindowById.throws(new Error("DB error"));
await getMaintenanceWindowById(req, res, next); await getMaintenanceWindowById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return success message with data if all operations are successful", async function () { it("should return success message with data if all operations are successful", async function() {
req.db.getMaintenanceWindowById.returns({ id: "123" }); req.db.getMaintenanceWindowById.returns({ id: "123" });
await getMaintenanceWindowById(req, res, next); await getMaintenanceWindowById(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID(req.language), msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
data: { id: "123" }, data: { id: "123" },
}) })
).to.be.true; ).to.be.true;
}); });
}); });
describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function () { describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function() {
let req, res, next, stub; let req, res, next, stub;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: {}, body: {},
params: {}, params: {},
@@ -179,7 +177,6 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
db: { db: {
getMaintenanceWindowsByTeamId: sinon.stub(), getMaintenanceWindowsByTeamId: sinon.stub(),
}, },
language: 'en',
}; };
res = { res = {
status: sinon.stub().returnsThis(), status: sinon.stub().returnsThis(),
@@ -188,7 +185,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
next = sinon.stub(); next = sinon.stub();
}); });
it("should reject if query validation fails", async function () { it("should reject if query validation fails", async function() {
req.query = { req.query = {
invalid: 1, invalid: 1,
}; };
@@ -197,14 +194,14 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject if jwt.verify fails", async function () { it("should reject if jwt.verify fails", async function() {
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError()); stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
await getMaintenanceWindowsByTeamId(req, res, next); await getMaintenanceWindowsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError); expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
stub.restore(); stub.restore();
}); });
it("should reject with an error if DB operations fail", async function () { it("should reject with an error if DB operations fail", async function() {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
@@ -215,7 +212,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
stub.restore(); stub.restore();
}); });
it("should return success message with data if all operations are successful", async function () { it("should return success message with data if all operations are successful", async function() {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
}); });
@@ -225,7 +222,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM(req.language), msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
data: [{ id: jwt.verify().teamId }], data: [{ id: jwt.verify().teamId }],
}) })
).to.be.true; ).to.be.true;
@@ -233,10 +230,10 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
}); });
}); });
describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", function () { describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: {}, body: {},
params: { params: {
@@ -260,25 +257,25 @@ describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", funct
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject if param validation fails", async function () { it("should reject if param validation fails", async function() {
req.params = {}; req.params = {};
await getMaintenanceWindowsByMonitorId(req, res, next); await getMaintenanceWindowsByMonitorId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if DB operations fail", async function () { it("should reject with an error if DB operations fail", async function() {
req.db.getMaintenanceWindowsByMonitorId.throws(new Error("DB error")); req.db.getMaintenanceWindowsByMonitorId.throws(new Error("DB error"));
await getMaintenanceWindowsByMonitorId(req, res, next); await getMaintenanceWindowsByMonitorId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return success message with data if all operations are successful", async function () { it("should return success message with data if all operations are successful", async function() {
const data = [{ monitorId: "123" }]; const data = [{ monitorId: "123" }];
req.db.getMaintenanceWindowsByMonitorId.returns(data); req.db.getMaintenanceWindowsByMonitorId.returns(data);
await getMaintenanceWindowsByMonitorId(req, res, next); await getMaintenanceWindowsByMonitorId(req, res, next);
@@ -287,17 +284,17 @@ describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", funct
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_MONITOR(req.language), msg: successMessages.MAINTENANCE_WINDOW_GET_BY_MONITOR,
data: data, data: data,
}) })
).to.be.true; ).to.be.true;
}); });
}); });
describe("maintenanceWindowController - deleteMaintenanceWindow", function () { describe("maintenanceWindowController - deleteMaintenanceWindow", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: {}, body: {},
params: { params: {
@@ -321,47 +318,46 @@ describe("maintenanceWindowController - deleteMaintenanceWindow", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject if param validation fails", async function () { it("should reject if param validation fails", async function() {
req.params = {}; req.params = {};
await deleteMaintenanceWindow(req, res, next); await deleteMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if DB operations fail", async function () { it("should reject with an error if DB operations fail", async function() {
req.db.deleteMaintenanceWindowById.throws(new Error("DB error")); req.db.deleteMaintenanceWindowById.throws(new Error("DB error"));
await deleteMaintenanceWindow(req, res, next); await deleteMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return success message if all operations are successful", async function () { it("should return success message if all operations are successful", async function() {
await deleteMaintenanceWindow(req, res, next); await deleteMaintenanceWindow(req, res, next);
expect(req.db.deleteMaintenanceWindowById.calledOnceWith(req.params.id)); expect(req.db.deleteMaintenanceWindowById.calledOnceWith(req.params.id));
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_DELETE(req.language), msg: successMessages.MAINTENANCE_WINDOW_DELETE,
}) })
).to.be.true; ).to.be.true;
}); });
}); });
describe("maintenanceWindowController - editMaintenanceWindow", function () { describe("maintenanceWindowController - editMaintenanceWindow", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: { body: {
active: true, active: true,
name: "test", name: "test",
}, },
language: 'en',
params: { params: {
id: "123", id: "123",
}, },
@@ -383,32 +379,32 @@ describe("maintenanceWindowController - editMaintenanceWindow", function () {
next = sinon.stub(); next = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should reject if param validation fails", async function () { it("should reject if param validation fails", async function() {
req.params = {}; req.params = {};
await editMaintenanceWindow(req, res, next); await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject if body validation fails", async function () { it("should reject if body validation fails", async function() {
req.body = { invalid: 1 }; req.body = { invalid: 1 };
await editMaintenanceWindow(req, res, next); await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422); expect(next.firstCall.args[0].status).to.equal(422);
}); });
it("should reject with an error if DB operations fail", async function () { it("should reject with an error if DB operations fail", async function() {
req.db.editMaintenanceWindowById.throws(new Error("DB error")); req.db.editMaintenanceWindowById.throws(new Error("DB error"));
await editMaintenanceWindow(req, res, next); await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return success message with data if all operations are successful", async function () { it("should return success message with data if all operations are successful", async function() {
const data = { id: "123" }; const data = { id: "123" };
req.db.editMaintenanceWindowById.returns(data); req.db.editMaintenanceWindowById.returns(data);
@@ -418,7 +414,7 @@ describe("maintenanceWindowController - editMaintenanceWindow", function () {
expect( expect(
res.json.calledOnceWith({ res.json.calledOnceWith({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_EDIT(req.language), msg: successMessages.MAINTENANCE_WINDOW_EDIT,
data: data, data: data,
}) })
).to.be.true; ).to.be.true;
File diff suppressed because it is too large. Load diff
@@ -8,10 +8,10 @@ import {
import { successMessages } from "../../utils/messages.js"; import { successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
describe("Queue Controller - getMetrics", function () { describe("Queue Controller - getMetrics", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
@@ -32,14 +32,14 @@ describe("Queue Controller - getMetrics", function () {
sinon.restore(); sinon.restore();
}); });
it("should throw an error if getMetrics throws an error", async function () { it("should throw an error if getMetrics throws an error", async function() {
req.jobQueue.getMetrics.throws(new Error("getMetrics error")); req.jobQueue.getMetrics.throws(new Error("getMetrics error"));
await getMetrics(req, res, next); await getMetrics(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getMetrics error"); expect(next.firstCall.args[0].message).to.equal("getMetrics error");
}); });
it("should return a success message and data if getMetrics is successful", async function () { it("should return a success message and data if getMetrics is successful", async function() {
const data = { data: "metrics" }; const data = { data: "metrics" };
req.jobQueue.getMetrics.returns(data); req.jobQueue.getMetrics.returns(data);
await getMetrics(req, res, next); await getMetrics(req, res, next);
@@ -52,10 +52,10 @@ describe("Queue Controller - getMetrics", function () {
}); });
}); });
describe("Queue Controller - getJobs", function () { describe("Queue Controller - getJobs", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
@@ -76,14 +76,14 @@ describe("Queue Controller - getJobs", function () {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if getJobs throws an error", async function () { it("should reject with an error if getJobs throws an error", async function() {
req.jobQueue.getJobStats.throws(new Error("getJobs error")); req.jobQueue.getJobStats.throws(new Error("getJobs error"));
await getJobs(req, res, next); await getJobs(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getJobs error"); expect(next.firstCall.args[0].message).to.equal("getJobs error");
}); });
it("should return a success message and data if getJobs is successful", async function () { it("should return a success message and data if getJobs is successful", async function() {
const data = { data: "jobs" }; const data = { data: "jobs" };
req.jobQueue.getJobStats.returns(data); req.jobQueue.getJobStats.returns(data);
await getJobs(req, res, next); await getJobs(req, res, next);
@@ -96,10 +96,10 @@ describe("Queue Controller - getJobs", function () {
}); });
}); });
describe("Queue Controller - addJob", function () { describe("Queue Controller - addJob", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
@@ -120,14 +120,14 @@ describe("Queue Controller - addJob", function () {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if addJob throws an error", async function () { it("should reject with an error if addJob throws an error", async function() {
req.jobQueue.addJob.throws(new Error("addJob error")); req.jobQueue.addJob.throws(new Error("addJob error"));
await addJob(req, res, next); await addJob(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("addJob error"); expect(next.firstCall.args[0].message).to.equal("addJob error");
}); });
it("should return a success message if addJob is successful", async function () { it("should return a success message if addJob is successful", async function() {
req.jobQueue.addJob.resolves(); req.jobQueue.addJob.resolves();
await addJob(req, res, next); await addJob(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
@@ -138,10 +138,10 @@ describe("Queue Controller - addJob", function () {
}); });
}); });
describe("Queue Controller - obliterateQueue", function () { describe("Queue Controller - obliterateQueue", function() {
let req, res, next; let req, res, next;
beforeEach(function () { beforeEach(function() {
req = { req = {
headers: {}, headers: {},
params: {}, params: {},
@@ -162,14 +162,14 @@ describe("Queue Controller - obliterateQueue", function () {
sinon.restore(); sinon.restore();
}); });
it("should reject with an error if obliterateQueue throws an error", async function () { it("should reject with an error if obliterateQueue throws an error", async function() {
req.jobQueue.obliterate.throws(new Error("obliterateQueue error")); req.jobQueue.obliterate.throws(new Error("obliterateQueue error"));
await obliterateQueue(req, res, next); await obliterateQueue(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("obliterateQueue error"); expect(next.firstCall.args[0].message).to.equal("obliterateQueue error");
}); });
it("should return a success message if obliterateQueue is successful", async function () { it("should return a success message if obliterateQueue is successful", async function() {
req.jobQueue.obliterate.resolves(); req.jobQueue.obliterate.resolves();
await obliterateQueue(req, res, next); await obliterateQueue(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(res.status.firstCall.args[0]).to.equal(200);
+16 -17
View File
@@ -7,33 +7,32 @@ import {
} from "../../db/mongo/modules/inviteModule.js"; } from "../../db/mongo/modules/inviteModule.js";
import { errorMessages } from "../../utils/messages.js"; import { errorMessages } from "../../utils/messages.js";
describe("Invite Module", function () { describe("Invite Module", function() {
const mockUserData = { const mockUserData = {
email: "test@test.com", email: "test@test.com",
teamId: "123", teamId: "123",
role: ["admin"], role: ["admin"],
token: "123", token: "123",
}; };
const mockLanguage = 'en';
const mockInviteToken = { _id: 123, time: 123 }; const mockInviteToken = { _id: 123, time: 123 };
let inviteTokenDeleteManyStub, let inviteTokenDeleteManyStub,
inviteTokenSaveStub, inviteTokenSaveStub,
inviteTokenFindOneStub, inviteTokenFindOneStub,
inviteTokenFindOneAndDeleteStub; inviteTokenFindOneAndDeleteStub;
beforeEach(function () { beforeEach(function() {
inviteTokenDeleteManyStub = sinon.stub(InviteToken, "deleteMany"); inviteTokenDeleteManyStub = sinon.stub(InviteToken, "deleteMany");
inviteTokenSaveStub = sinon.stub(InviteToken.prototype, "save"); inviteTokenSaveStub = sinon.stub(InviteToken.prototype, "save");
inviteTokenFindOneStub = sinon.stub(InviteToken, "findOne"); inviteTokenFindOneStub = sinon.stub(InviteToken, "findOne");
inviteTokenFindOneAndDeleteStub = sinon.stub(InviteToken, "findOneAndDelete"); inviteTokenFindOneAndDeleteStub = sinon.stub(InviteToken, "findOneAndDelete");
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
describe("requestInviteToken", function () { describe("requestInviteToken", function() {
it("should return a new invite token", async function () { it("should return a new invite token", async function() {
inviteTokenDeleteManyStub.resolves(); inviteTokenDeleteManyStub.resolves();
inviteTokenSaveStub.resolves(); inviteTokenSaveStub.resolves();
const inviteToken = await requestInviteToken(mockUserData); const inviteToken = await requestInviteToken(mockUserData);
@@ -42,7 +41,7 @@ describe("Invite Module", function () {
expect(inviteToken.token).to.exist; expect(inviteToken.token).to.exist;
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("test error"); const err = new Error("test error");
inviteTokenDeleteManyStub.rejects(err); inviteTokenDeleteManyStub.rejects(err);
try { try {
@@ -53,23 +52,23 @@ describe("Invite Module", function () {
}); });
}); });
describe("getInviteToken", function () { describe("getInviteToken", function() {
it("should return an invite token", async function () { it("should return an invite token", async function() {
inviteTokenFindOneStub.resolves(mockInviteToken); inviteTokenFindOneStub.resolves(mockInviteToken);
const inviteToken = await getInviteToken(mockUserData.token); const inviteToken = await getInviteToken(mockUserData.token);
expect(inviteToken).to.deep.equal(mockInviteToken); expect(inviteToken).to.deep.equal(mockInviteToken);
}); });
it("should handle a token not found", async function () { it("should handle a token not found", async function() {
inviteTokenFindOneStub.resolves(null); inviteTokenFindOneStub.resolves(null);
try { try {
await getInviteToken(mockUserData.token); await getInviteToken(mockUserData.token);
} catch (error) { } catch (error) {
expect(error.message).to.equal(errorMessages.AUTH_INVITE_NOT_FOUND(mockLanguage)); expect(error.message).to.equal(errorMessages.AUTH_INVITE_NOT_FOUND);
} }
}); });
it("should handle DB errors", async function () { it("should handle DB errors", async function() {
const err = new Error("test error"); const err = new Error("test error");
inviteTokenFindOneStub.rejects(err); inviteTokenFindOneStub.rejects(err);
try { try {
@@ -81,23 +80,23 @@ describe("Invite Module", function () {
}); });
}); });
describe("getInviteTokenAndDelete", function () { describe("getInviteTokenAndDelete", function() {
it("should return a deleted invite", async function () { it("should return a deleted invite", async function() {
inviteTokenFindOneAndDeleteStub.resolves(mockInviteToken); inviteTokenFindOneAndDeleteStub.resolves(mockInviteToken);
const deletedInvite = await getInviteTokenAndDelete(mockUserData.token); const deletedInvite = await getInviteTokenAndDelete(mockUserData.token);
expect(deletedInvite).to.deep.equal(mockInviteToken); expect(deletedInvite).to.deep.equal(mockInviteToken);
}); });
it("should handle a token not found", async function () { it("should handle a token not found", async function() {
inviteTokenFindOneAndDeleteStub.resolves(null); inviteTokenFindOneAndDeleteStub.resolves(null);
try { try {
await getInviteTokenAndDelete(mockUserData.token); await getInviteTokenAndDelete(mockUserData.token);
} catch (error) { } catch (error) {
expect(error.message).to.equal(errorMessages.AUTH_INVITE_NOT_FOUND(mockLanguage)); expect(error.message).to.equal(errorMessages.AUTH_INVITE_NOT_FOUND);
} }
}); });
it("should handle DB errors", async function () { it("should handle DB errors", async function() {
const err = new Error("test error"); const err = new Error("test error");
inviteTokenFindOneAndDeleteStub.rejects(err); inviteTokenFindOneAndDeleteStub.rejects(err);
try { try {
+141 -143
View File
@@ -31,7 +31,7 @@ import {
calculateGroupStats, calculateGroupStats,
} from "../../db/mongo/modules/monitorModule.js"; } from "../../db/mongo/modules/monitorModule.js";
describe("monitorModule", function () { describe("monitorModule", function() {
let monitorFindStub, let monitorFindStub,
monitorFindByIdStub, monitorFindByIdStub,
monitorFindByIdAndUpdateStub, monitorFindByIdAndUpdateStub,
@@ -43,7 +43,7 @@ describe("monitorModule", function () {
pageSpeedCheckFindStub, pageSpeedCheckFindStub,
hardwareCheckFindStub; hardwareCheckFindStub;
beforeEach(function () { beforeEach(function() {
monitorFindStub = sinon.stub(Monitor, "find"); monitorFindStub = sinon.stub(Monitor, "find");
monitorFindByIdStub = sinon.stub(Monitor, "findById"); monitorFindByIdStub = sinon.stub(Monitor, "findById");
monitorFindByIdAndUpdateStub = sinon.stub(Monitor, "findByIdAndUpdate"); monitorFindByIdAndUpdateStub = sinon.stub(Monitor, "findByIdAndUpdate");
@@ -63,12 +63,12 @@ describe("monitorModule", function () {
}); });
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
describe("getAllMonitors", function () { describe("getAllMonitors", function() {
it("should return all monitors", async function () { it("should return all monitors", async function() {
const mockMonitors = [ const mockMonitors = [
{ _id: "1", name: "Monitor 1", url: "test1.com" }, { _id: "1", name: "Monitor 1", url: "test1.com" },
{ _id: "2", name: "Monitor 2", url: "test2.com" }, { _id: "2", name: "Monitor 2", url: "test2.com" },
@@ -81,13 +81,13 @@ describe("monitorModule", function () {
expect(monitorFindStub.firstCall.args).to.deep.equal([]); expect(monitorFindStub.firstCall.args).to.deep.equal([]);
}); });
it("should handle empty results", async function () { it("should handle empty results", async function() {
monitorFindStub.returns([]); monitorFindStub.returns([]);
const result = await getAllMonitors(); const result = await getAllMonitors();
expect(result).to.be.an("array").that.is.empty; expect(result).to.be.an("array").that.is.empty;
}); });
it("should throw error when database fails", async function () { it("should throw error when database fails", async function() {
// Arrange // Arrange
const error = new Error("Database error"); const error = new Error("Database error");
error.service = "MonitorModule"; error.service = "MonitorModule";
@@ -105,8 +105,8 @@ describe("monitorModule", function () {
}); });
}); });
describe("getAllMonitorsWithUptimeStats", function () { describe("getAllMonitorsWithUptimeStats", function() {
it("should return monitors with uptime stats for different time periods", async function () { it("should return monitors with uptime stats for different time periods", async function() {
// Mock data // Mock data
const mockMonitors = [ const mockMonitors = [
{ {
@@ -152,7 +152,7 @@ describe("monitorModule", function () {
expect(monitor["90"]).to.equal(75); expect(monitor["90"]).to.equal(75);
}); });
it("should return monitors with stats for pagespeed type", async function () { it("should return monitors with stats for pagespeed type", async function() {
// Mock data // Mock data
const mockMonitors = [ const mockMonitors = [
{ {
@@ -198,7 +198,7 @@ describe("monitorModule", function () {
expect(monitor["90"]).to.equal(75); expect(monitor["90"]).to.equal(75);
}); });
it("should return monitors with stats for hardware type", async function () { it("should return monitors with stats for hardware type", async function() {
// Mock data // Mock data
const mockMonitors = [ const mockMonitors = [
{ {
@@ -244,7 +244,7 @@ describe("monitorModule", function () {
expect(monitor["90"]).to.equal(75); expect(monitor["90"]).to.equal(75);
}); });
it("should handle errors appropriately", async function () { it("should handle errors appropriately", async function() {
// Setup stub to throw error // Setup stub to throw error
monitorFindStub.rejects(new Error("Database error")); monitorFindStub.rejects(new Error("Database error"));
@@ -258,7 +258,7 @@ describe("monitorModule", function () {
} }
}); });
it("should handle empty monitor list", async function () { it("should handle empty monitor list", async function() {
monitorFindStub.resolves([]); monitorFindStub.resolves([]);
const result = await getAllMonitorsWithUptimeStats(); const result = await getAllMonitorsWithUptimeStats();
@@ -267,7 +267,7 @@ describe("monitorModule", function () {
expect(result).to.have.lengthOf(0); expect(result).to.have.lengthOf(0);
}); });
it("should handle monitor with no checks", async function () { it("should handle monitor with no checks", async function() {
const mockMonitors = [ const mockMonitors = [
{ {
_id: "monitor1", _id: "monitor1",
@@ -292,28 +292,28 @@ describe("monitorModule", function () {
}); });
}); });
describe("calculateUptimeDuration", function () { describe("calculateUptimeDuration", function() {
let clock; let clock;
const NOW = new Date("2024-01-01T12:00:00Z").getTime(); const NOW = new Date("2024-01-01T12:00:00Z").getTime();
beforeEach(function () { beforeEach(function() {
// Fix the current time // Fix the current time
clock = sinon.useFakeTimers(NOW); clock = sinon.useFakeTimers(NOW);
}); });
afterEach(function () { afterEach(function() {
clock.restore(); clock.restore();
}); });
it("should return 0 when checks array is empty", function () { it("should return 0 when checks array is empty", function() {
expect(calculateUptimeDuration([])).to.equal(0); expect(calculateUptimeDuration([])).to.equal(0);
}); });
it("should return 0 when checks array is null", function () { it("should return 0 when checks array is null", function() {
expect(calculateUptimeDuration(null)).to.equal(0); expect(calculateUptimeDuration(null)).to.equal(0);
}); });
it("should calculate uptime from last down check to most recent check", function () { it("should calculate uptime from last down check to most recent check", function() {
const checks = [ const checks = [
{ status: true, createdAt: "2024-01-01T11:00:00Z" }, // Most recent { status: true, createdAt: "2024-01-01T11:00:00Z" }, // Most recent
{ status: true, createdAt: "2024-01-01T10:00:00Z" }, { status: true, createdAt: "2024-01-01T10:00:00Z" },
@@ -325,7 +325,7 @@ describe("monitorModule", function () {
expect(calculateUptimeDuration(checks)).to.equal(7200000); expect(calculateUptimeDuration(checks)).to.equal(7200000);
}); });
it("should calculate uptime from first check when no down checks exist", function () { it("should calculate uptime from first check when no down checks exist", function() {
const checks = [ const checks = [
{ status: true, createdAt: "2024-01-01T11:00:00Z" }, { status: true, createdAt: "2024-01-01T11:00:00Z" },
{ status: true, createdAt: "2024-01-01T10:00:00Z" }, { status: true, createdAt: "2024-01-01T10:00:00Z" },
@@ -337,28 +337,28 @@ describe("monitorModule", function () {
}); });
}); });
describe("getLastChecked", function () { describe("getLastChecked", function() {
let clock; let clock;
const NOW = new Date("2024-01-01T12:00:00Z").getTime(); const NOW = new Date("2024-01-01T12:00:00Z").getTime();
beforeEach(function () { beforeEach(function() {
// Fix the current time // Fix the current time
clock = sinon.useFakeTimers(NOW); clock = sinon.useFakeTimers(NOW);
}); });
afterEach(function () { afterEach(function() {
clock.restore(); clock.restore();
}); });
it("should return 0 when checks array is empty", function () { it("should return 0 when checks array is empty", function() {
expect(getLastChecked([])).to.equal(0); expect(getLastChecked([])).to.equal(0);
}); });
it("should return 0 when checks array is null", function () { it("should return 0 when checks array is null", function() {
expect(getLastChecked(null)).to.equal(0); expect(getLastChecked(null)).to.equal(0);
}); });
it("should return time difference between now and most recent check", function () { it("should return time difference between now and most recent check", function() {
const checks = [ const checks = [
{ createdAt: "2024-01-01T11:30:00Z" }, // 30 minutes ago { createdAt: "2024-01-01T11:30:00Z" }, // 30 minutes ago
{ createdAt: "2024-01-01T11:00:00Z" }, { createdAt: "2024-01-01T11:00:00Z" },
@@ -369,7 +369,7 @@ describe("monitorModule", function () {
expect(getLastChecked(checks)).to.equal(1800000); expect(getLastChecked(checks)).to.equal(1800000);
}); });
it("should handle checks from different days", function () { it("should handle checks from different days", function() {
const checks = [ const checks = [
{ createdAt: "2023-12-31T12:00:00Z" }, // 24 hours ago { createdAt: "2023-12-31T12:00:00Z" }, // 24 hours ago
{ createdAt: "2023-12-30T12:00:00Z" }, { createdAt: "2023-12-30T12:00:00Z" },
@@ -380,16 +380,16 @@ describe("monitorModule", function () {
}); });
}); });
describe("getLatestResponseTime", function () { describe("getLatestResponseTime", function() {
it("should return 0 when checks array is empty", function () { it("should return 0 when checks array is empty", function() {
expect(getLatestResponseTime([])).to.equal(0); expect(getLatestResponseTime([])).to.equal(0);
}); });
it("should return 0 when checks array is null", function () { it("should return 0 when checks array is null", function() {
expect(getLatestResponseTime(null)).to.equal(0); expect(getLatestResponseTime(null)).to.equal(0);
}); });
it("should return response time from most recent check", function () { it("should return response time from most recent check", function() {
const checks = [ const checks = [
{ responseTime: 150, createdAt: "2024-01-01T11:30:00Z" }, // Most recent { responseTime: 150, createdAt: "2024-01-01T11:30:00Z" }, // Most recent
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" }, { responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -399,7 +399,7 @@ describe("monitorModule", function () {
expect(getLatestResponseTime(checks)).to.equal(150); expect(getLatestResponseTime(checks)).to.equal(150);
}); });
it("should handle missing responseTime in checks", function () { it("should handle missing responseTime in checks", function() {
const checks = [ const checks = [
{ createdAt: "2024-01-01T11:30:00Z" }, { createdAt: "2024-01-01T11:30:00Z" },
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" }, { responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -409,16 +409,16 @@ describe("monitorModule", function () {
}); });
}); });
describe("getAverageResponseTime", function () { describe("getAverageResponseTime", function() {
it("should return 0 when checks array is empty", function () { it("should return 0 when checks array is empty", function() {
expect(getAverageResponseTime([])).to.equal(0); expect(getAverageResponseTime([])).to.equal(0);
}); });
it("should return 0 when checks array is null", function () { it("should return 0 when checks array is null", function() {
expect(getAverageResponseTime(null)).to.equal(0); expect(getAverageResponseTime(null)).to.equal(0);
}); });
it("should calculate average response time from all checks", function () { it("should calculate average response time from all checks", function() {
const checks = [ const checks = [
{ responseTime: 100, createdAt: "2024-01-01T11:30:00Z" }, { responseTime: 100, createdAt: "2024-01-01T11:30:00Z" },
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" }, { responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -429,7 +429,7 @@ describe("monitorModule", function () {
expect(getAverageResponseTime(checks)).to.equal(200); expect(getAverageResponseTime(checks)).to.equal(200);
}); });
it("should handle missing responseTime in some checks", function () { it("should handle missing responseTime in some checks", function() {
const checks = [ const checks = [
{ responseTime: 100, createdAt: "2024-01-01T11:30:00Z" }, { responseTime: 100, createdAt: "2024-01-01T11:30:00Z" },
{ createdAt: "2024-01-01T11:00:00Z" }, { createdAt: "2024-01-01T11:00:00Z" },
@@ -440,7 +440,7 @@ describe("monitorModule", function () {
expect(getAverageResponseTime(checks)).to.equal(200); expect(getAverageResponseTime(checks)).to.equal(200);
}); });
it("should return 0 when no checks have responseTime", function () { it("should return 0 when no checks have responseTime", function() {
const checks = [ const checks = [
{ createdAt: "2024-01-01T11:30:00Z" }, { createdAt: "2024-01-01T11:30:00Z" },
{ createdAt: "2024-01-01T11:00:00Z" }, { createdAt: "2024-01-01T11:00:00Z" },
@@ -450,26 +450,26 @@ describe("monitorModule", function () {
}); });
}); });
describe("getUptimePercentage", function () { describe("getUptimePercentage", function() {
it("should return 0 when checks array is empty", function () { it("should return 0 when checks array is empty", function() {
expect(getUptimePercentage([])).to.equal(0); expect(getUptimePercentage([])).to.equal(0);
}); });
it("should return 0 when checks array is null", function () { it("should return 0 when checks array is null", function() {
expect(getUptimePercentage(null)).to.equal(0); expect(getUptimePercentage(null)).to.equal(0);
}); });
it("should return 100 when all checks are up", function () { it("should return 100 when all checks are up", function() {
const checks = [{ status: true }, { status: true }, { status: true }]; const checks = [{ status: true }, { status: true }, { status: true }];
expect(getUptimePercentage(checks)).to.equal(100); expect(getUptimePercentage(checks)).to.equal(100);
}); });
it("should return 0 when all checks are down", function () { it("should return 0 when all checks are down", function() {
const checks = [{ status: false }, { status: false }, { status: false }]; const checks = [{ status: false }, { status: false }, { status: false }];
expect(getUptimePercentage(checks)).to.equal(0); expect(getUptimePercentage(checks)).to.equal(0);
}); });
it("should calculate correct percentage for mixed status checks", function () { it("should calculate correct percentage for mixed status checks", function() {
const checks = [ const checks = [
{ status: true }, { status: true },
{ status: false }, { status: false },
@@ -480,33 +480,33 @@ describe("monitorModule", function () {
expect(getUptimePercentage(checks)).to.equal(75); expect(getUptimePercentage(checks)).to.equal(75);
}); });
it("should handle undefined status values", function () { it("should handle undefined status values", function() {
const checks = [{ status: true }, { status: undefined }, { status: true }]; const checks = [{ status: true }, { status: undefined }, { status: true }];
// 2 up out of 3 total ≈ 66.67% // 2 up out of 3 total ≈ 66.67%
expect(getUptimePercentage(checks)).to.equal((2 / 3) * 100); expect(getUptimePercentage(checks)).to.equal((2 / 3) * 100);
}); });
}); });
describe("getIncidents", function () { describe("getIncidents", function() {
it("should return 0 when checks array is empty", function () { it("should return 0 when checks array is empty", function() {
expect(getIncidents([])).to.equal(0); expect(getIncidents([])).to.equal(0);
}); });
it("should return 0 when checks array is null", function () { it("should return 0 when checks array is null", function() {
expect(getIncidents(null)).to.equal(0); expect(getIncidents(null)).to.equal(0);
}); });
it("should return 0 when all checks are up", function () { it("should return 0 when all checks are up", function() {
const checks = [{ status: true }, { status: true }, { status: true }]; const checks = [{ status: true }, { status: true }, { status: true }];
expect(getIncidents(checks)).to.equal(0); expect(getIncidents(checks)).to.equal(0);
}); });
it("should count all incidents when all checks are down", function () { it("should count all incidents when all checks are down", function() {
const checks = [{ status: false }, { status: false }, { status: false }]; const checks = [{ status: false }, { status: false }, { status: false }];
expect(getIncidents(checks)).to.equal(3); expect(getIncidents(checks)).to.equal(3);
}); });
it("should count correct number of incidents for mixed status checks", function () { it("should count correct number of incidents for mixed status checks", function() {
const checks = [ const checks = [
{ status: true }, { status: true },
{ status: false }, { status: false },
@@ -517,7 +517,7 @@ describe("monitorModule", function () {
expect(getIncidents(checks)).to.equal(2); expect(getIncidents(checks)).to.equal(2);
}); });
it("should handle undefined status values", function () { it("should handle undefined status values", function() {
const checks = [ const checks = [
{ status: true }, { status: true },
{ status: undefined }, { status: undefined },
@@ -529,10 +529,10 @@ describe("monitorModule", function () {
}); });
}); });
describe("getMonitorChecks", function () { describe("getMonitorChecks", function() {
let mockModel; let mockModel;
beforeEach(function () { beforeEach(function() {
// Create a mock model with chainable methods // Create a mock model with chainable methods
const mockChecks = [ const mockChecks = [
{ monitorId: "123", createdAt: new Date("2024-01-01") }, { monitorId: "123", createdAt: new Date("2024-01-01") },
@@ -546,11 +546,11 @@ describe("monitorModule", function () {
}; };
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should return all checks and date-ranged checks", async function () { it("should return all checks and date-ranged checks", async function() {
// Arrange // Arrange
const monitorId = "123"; const monitorId = "123";
const dateRange = { const dateRange = {
@@ -579,7 +579,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle empty results", async function () { it("should handle empty results", async function() {
// Arrange // Arrange
const emptyModel = { const emptyModel = {
find: sinon.stub().returns({ find: sinon.stub().returns({
@@ -603,7 +603,7 @@ describe("monitorModule", function () {
expect(result.checksForDateRange).to.be.an("array").that.is.empty; expect(result.checksForDateRange).to.be.an("array").that.is.empty;
}); });
it("should maintain sort order", async function () { it("should maintain sort order", async function() {
// Arrange // Arrange
const sortedChecks = [ const sortedChecks = [
{ monitorId: "123", createdAt: new Date("2024-01-02") }, { monitorId: "123", createdAt: new Date("2024-01-02") },
@@ -637,39 +637,39 @@ describe("monitorModule", function () {
}); });
}); });
describe("processChecksForDisplay", function () { describe("processChecksForDisplay", function() {
let normalizeStub; let normalizeStub;
beforeEach(function () { beforeEach(function() {
normalizeStub = sinon.stub(); normalizeStub = sinon.stub();
}); });
it("should return original checks when numToDisplay is not provided", function () { it("should return original checks when numToDisplay is not provided", function() {
const checks = [1, 2, 3, 4, 5]; const checks = [1, 2, 3, 4, 5];
const result = processChecksForDisplay(normalizeStub, checks); const result = processChecksForDisplay(normalizeStub, checks);
expect(result).to.deep.equal(checks); expect(result).to.deep.equal(checks);
}); });
it("should return original checks when numToDisplay is greater than checks length", function () { it("should return original checks when numToDisplay is greater than checks length", function() {
const checks = [1, 2, 3]; const checks = [1, 2, 3];
const result = processChecksForDisplay(normalizeStub, checks, 5); const result = processChecksForDisplay(normalizeStub, checks, 5);
expect(result).to.deep.equal(checks); expect(result).to.deep.equal(checks);
}); });
it("should filter checks based on numToDisplay", function () { it("should filter checks based on numToDisplay", function() {
const checks = [1, 2, 3, 4, 5, 6]; const checks = [1, 2, 3, 4, 5, 6];
const result = processChecksForDisplay(normalizeStub, checks, 3); const result = processChecksForDisplay(normalizeStub, checks, 3);
// Should return [1, 3, 5] as n = ceil(6/3) = 2 // Should return [1, 3, 5] as n = ceil(6/3) = 2
expect(result).to.deep.equal([1, 3, 5]); expect(result).to.deep.equal([1, 3, 5]);
}); });
it("should handle empty checks array", function () { it("should handle empty checks array", function() {
const checks = []; const checks = [];
const result = processChecksForDisplay(normalizeStub, checks, 3); const result = processChecksForDisplay(normalizeStub, checks, 3);
expect(result).to.be.an("array").that.is.empty; expect(result).to.be.an("array").that.is.empty;
}); });
it("should call normalizeData when normalize is true", function () { it("should call normalizeData when normalize is true", function() {
const checks = [1, 2, 3]; const checks = [1, 2, 3];
normalizeStub.returns([10, 20, 30]); normalizeStub.returns([10, 20, 30]);
@@ -679,7 +679,7 @@ describe("monitorModule", function () {
expect(result).to.deep.equal([10, 20, 30]); expect(result).to.deep.equal([10, 20, 30]);
}); });
it("should handle both filtering and normalization", function () { it("should handle both filtering and normalization", function() {
const checks = [1, 2, 3, 4, 5, 6]; const checks = [1, 2, 3, 4, 5, 6];
normalizeStub.returns([10, 30, 50]); normalizeStub.returns([10, 30, 50]);
@@ -690,7 +690,7 @@ describe("monitorModule", function () {
}); });
}); });
describe("groupChecksByTime", function () { describe("groupChecksByTime", function() {
const mockChecks = [ const mockChecks = [
{ createdAt: "2024-01-15T10:30:45Z" }, { createdAt: "2024-01-15T10:30:45Z" },
{ createdAt: "2024-01-15T10:45:15Z" }, { createdAt: "2024-01-15T10:45:15Z" },
@@ -698,7 +698,7 @@ describe("monitorModule", function () {
{ createdAt: "2024-01-16T10:30:00Z" }, { createdAt: "2024-01-16T10:30:00Z" },
]; ];
it("should group checks by hour when dateRange is 'day'", function () { it("should group checks by hour when dateRange is 'day'", function() {
const result = groupChecksByTime(mockChecks, "day"); const result = groupChecksByTime(mockChecks, "day");
// Get timestamps for 10:00 and 11:00 on Jan 15 // Get timestamps for 10:00 and 11:00 on Jan 15
@@ -713,7 +713,7 @@ describe("monitorModule", function () {
expect(result[time3].checks).to.have.lengthOf(1); expect(result[time3].checks).to.have.lengthOf(1);
}); });
it("should group checks by day when dateRange is not 'day'", function () { it("should group checks by day when dateRange is not 'day'", function() {
const result = groupChecksByTime(mockChecks, "week"); const result = groupChecksByTime(mockChecks, "week");
expect(Object.keys(result)).to.have.lengthOf(2); expect(Object.keys(result)).to.have.lengthOf(2);
@@ -721,12 +721,12 @@ describe("monitorModule", function () {
expect(result["2024-01-16"].checks).to.have.lengthOf(1); expect(result["2024-01-16"].checks).to.have.lengthOf(1);
}); });
it("should handle empty checks array", function () { it("should handle empty checks array", function() {
const result = groupChecksByTime([], "day"); const result = groupChecksByTime([], "day");
expect(result).to.deep.equal({}); expect(result).to.deep.equal({});
}); });
it("should handle single check", function () { it("should handle single check", function() {
const singleCheck = [{ createdAt: "2024-01-15T10:30:45Z" }]; const singleCheck = [{ createdAt: "2024-01-15T10:30:45Z" }];
const result = groupChecksByTime(singleCheck, "day"); const result = groupChecksByTime(singleCheck, "day");
@@ -735,7 +735,7 @@ describe("monitorModule", function () {
expect(result[expectedTime].checks).to.have.lengthOf(1); expect(result[expectedTime].checks).to.have.lengthOf(1);
}); });
it("should skip invalid dates and process valid ones", function () { it("should skip invalid dates and process valid ones", function() {
const checksWithInvalidDate = [ const checksWithInvalidDate = [
{ createdAt: "invalid-date" }, { createdAt: "invalid-date" },
{ createdAt: "2024-01-15T10:30:45Z" }, { createdAt: "2024-01-15T10:30:45Z" },
@@ -752,7 +752,7 @@ describe("monitorModule", function () {
expect(result[expectedTime].checks[0].createdAt).to.equal("2024-01-15T10:30:45Z"); expect(result[expectedTime].checks[0].createdAt).to.equal("2024-01-15T10:30:45Z");
}); });
it("should handle checks in same time group", function () { it("should handle checks in same time group", function() {
const checksInSameHour = [ const checksInSameHour = [
{ createdAt: "2024-01-15T10:15:00Z" }, { createdAt: "2024-01-15T10:15:00Z" },
{ createdAt: "2024-01-15T10:45:00Z" }, { createdAt: "2024-01-15T10:45:00Z" },
@@ -766,16 +766,16 @@ describe("monitorModule", function () {
}); });
}); });
describe("calculateGroupStats", function () { describe("calculateGroupStats", function() {
// Mock getUptimePercentage function // Mock getUptimePercentage function
let uptimePercentageStub; let uptimePercentageStub;
beforeEach(function () { beforeEach(function() {
uptimePercentageStub = sinon.stub(); uptimePercentageStub = sinon.stub();
uptimePercentageStub.returns(95); // Default return value uptimePercentageStub.returns(95); // Default return value
}); });
it("should calculate stats correctly for a group of checks", function () { it("should calculate stats correctly for a group of checks", function() {
const mockGroup = { const mockGroup = {
time: "2024-01-15", time: "2024-01-15",
checks: [ checks: [
@@ -796,7 +796,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle empty checks array", function () { it("should handle empty checks array", function() {
const mockGroup = { const mockGroup = {
time: "2024-01-15", time: "2024-01-15",
checks: [], checks: [],
@@ -813,7 +813,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle missing responseTime values", function () { it("should handle missing responseTime values", function() {
const mockGroup = { const mockGroup = {
time: "2024-01-15", time: "2024-01-15",
checks: [ checks: [
@@ -834,7 +834,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle all checks with status false", function () { it("should handle all checks with status false", function() {
const mockGroup = { const mockGroup = {
time: "2024-01-15", time: "2024-01-15",
checks: [ checks: [
@@ -855,7 +855,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle all checks with status true", function () { it("should handle all checks with status true", function() {
const mockGroup = { const mockGroup = {
time: "2024-01-15", time: "2024-01-15",
checks: [ checks: [
@@ -877,7 +877,7 @@ describe("monitorModule", function () {
}); });
}); });
describe("getMonitorStatsById", function () { describe("getMonitorStatsById", function() {
const now = new Date(); const now = new Date();
const oneHourAgo = new Date(now - 3600000); const oneHourAgo = new Date(now - 3600000);
const twoHoursAgo = new Date(now - 7200000); const twoHoursAgo = new Date(now - 7200000);
@@ -974,18 +974,18 @@ describe("monitorModule", function () {
}, },
}; };
beforeEach(function () { beforeEach(function() {
checkFindStub.returns({ checkFindStub.returns({
sort: () => checkDocs, sort: () => checkDocs,
}); });
monitorFindByIdStub.returns(mockMonitor); monitorFindByIdStub.returns(mockMonitor);
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should return monitor stats with calculated values, sort order desc", async function () { it("should return monitor stats with calculated values, sort order desc", async function() {
req.query.sortOrder = "desc"; req.query.sortOrder = "desc";
const result = await getMonitorStatsById(req); const result = await getMonitorStatsById(req);
expect(result).to.include.keys([ expect(result).to.include.keys([
@@ -1009,7 +1009,7 @@ describe("monitorModule", function () {
expect(result.aggregateData).to.be.an("array"); expect(result.aggregateData).to.be.an("array");
}); });
it("should return monitor stats with calculated values, ping type", async function () { it("should return monitor stats with calculated values, ping type", async function() {
monitorFindByIdStub.returns(mockMonitorPing); monitorFindByIdStub.returns(mockMonitorPing);
req.query.sortOrder = "desc"; req.query.sortOrder = "desc";
const result = await getMonitorStatsById(req); const result = await getMonitorStatsById(req);
@@ -1034,7 +1034,7 @@ describe("monitorModule", function () {
expect(result.aggregateData).to.be.an("array"); expect(result.aggregateData).to.be.an("array");
}); });
it("should return monitor stats with calculated values, docker type", async function () { it("should return monitor stats with calculated values, docker type", async function() {
monitorFindByIdStub.returns(mockMonitorDocker); monitorFindByIdStub.returns(mockMonitorDocker);
req.query.sortOrder = "desc"; req.query.sortOrder = "desc";
const result = await getMonitorStatsById(req); const result = await getMonitorStatsById(req);
@@ -1059,7 +1059,7 @@ describe("monitorModule", function () {
expect(result.aggregateData).to.be.an("array"); expect(result.aggregateData).to.be.an("array");
}); });
it("should return monitor stats with calculated values", async function () { it("should return monitor stats with calculated values", async function() {
req.query.sortOrder = "asc"; req.query.sortOrder = "asc";
const result = await getMonitorStatsById(req); const result = await getMonitorStatsById(req);
expect(result).to.include.keys([ expect(result).to.include.keys([
@@ -1083,7 +1083,7 @@ describe("monitorModule", function () {
expect(result.aggregateData).to.be.an("array"); expect(result.aggregateData).to.be.an("array");
}); });
it("should throw error when monitor is not found", async function () { it("should throw error when monitor is not found", async function() {
monitorFindByIdStub.returns(Promise.resolve(null)); monitorFindByIdStub.returns(Promise.resolve(null));
const req = { const req = {
@@ -1101,21 +1101,21 @@ describe("monitorModule", function () {
}); });
}); });
describe("getMonitorById", function () { describe("getMonitorById", function() {
let notificationFindStub; let notificationFindStub;
let monitorSaveStub; let monitorSaveStub;
beforeEach(function () { beforeEach(function() {
// Create stubs // Create stubs
notificationFindStub = sinon.stub(Notification, "find"); notificationFindStub = sinon.stub(Notification, "find");
monitorSaveStub = sinon.stub().resolves(); monitorSaveStub = sinon.stub().resolves();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should return monitor with notifications when found", async function () { it("should return monitor with notifications when found", async function() {
// Arrange // Arrange
const monitorId = "123"; const monitorId = "123";
const mockMonitor = { const mockMonitor = {
@@ -1139,10 +1139,9 @@ describe("monitorModule", function () {
expect(monitorSaveStub.calledOnce).to.be.true; expect(monitorSaveStub.calledOnce).to.be.true;
}); });
it("should throw 404 error when monitor not found", async function () { it("should throw 404 error when monitor not found", async function() {
// Arrange // Arrange
const monitorId = "nonexistent"; const monitorId = "nonexistent";
const mockLanguage = 'en';
monitorFindByIdStub.resolves(null); monitorFindByIdStub.resolves(null);
// Act & Assert // Act & Assert
@@ -1150,14 +1149,14 @@ describe("monitorModule", function () {
await getMonitorById(monitorId); await getMonitorById(monitorId);
expect.fail("Should have thrown an error"); expect.fail("Should have thrown an error");
} catch (error) { } catch (error) {
expect(error.message).to.equal(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId, mockLanguage)); expect(error.message).to.equal(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
expect(error.status).to.equal(404); expect(error.status).to.equal(404);
expect(error.service).to.equal("monitorModule"); expect(error.service).to.equal("monitorModule");
expect(error.method).to.equal("getMonitorById"); expect(error.method).to.equal("getMonitorById");
} }
}); });
it("should handle database errors properly", async function () { it("should handle database errors properly", async function() {
// Arrange // Arrange
const monitorId = "123"; const monitorId = "123";
const dbError = new Error("Database connection failed"); const dbError = new Error("Database connection failed");
@@ -1174,7 +1173,7 @@ describe("monitorModule", function () {
} }
}); });
it("should handle notification fetch errors", async function () { it("should handle notification fetch errors", async function() {
// Arrange // Arrange
const monitorId = "123"; const monitorId = "123";
const mockMonitor = { const mockMonitor = {
@@ -1198,7 +1197,7 @@ describe("monitorModule", function () {
} }
}); });
it("should handle monitor save errors", async function () { it("should handle monitor save errors", async function() {
// Arrange // Arrange
const monitorId = "123"; const monitorId = "123";
const mockMonitor = { const mockMonitor = {
@@ -1223,8 +1222,8 @@ describe("monitorModule", function () {
}); });
}); });
describe("getMonitorsAndSummaryByTeamId", function () { describe("getMonitorsAndSummaryByTeamId", function() {
it("should return monitors and correct summary counts", async function () { it("should return monitors and correct summary counts", async function() {
// Arrange // Arrange
const teamId = "team123"; const teamId = "team123";
const type = "http"; const type = "http";
@@ -1250,7 +1249,7 @@ describe("monitorModule", function () {
expect(monitorFindStub.calledOnceWith({ teamId, type })).to.be.true; expect(monitorFindStub.calledOnceWith({ teamId, type })).to.be.true;
}); });
it("should return empty results for non-existent team", async function () { it("should return empty results for non-existent team", async function() {
// Arrange // Arrange
monitorFindStub.resolves([]); monitorFindStub.resolves([]);
@@ -1267,7 +1266,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle database errors", async function () { it("should handle database errors", async function() {
// Arrange // Arrange
const error = new Error("Database error"); const error = new Error("Database error");
error.service = "MonitorModule"; error.service = "MonitorModule";
@@ -1286,8 +1285,8 @@ describe("monitorModule", function () {
}); });
}); });
describe("getMonitorsByTeamId", function () { describe("getMonitorsByTeamId", function() {
beforeEach(function () { beforeEach(function() {
// Chain stubs for Monitor.find().skip().limit().sort() // Chain stubs for Monitor.find().skip().limit().sort()
// Stub for CHECK_MODEL_LOOKUP model find // Stub for CHECK_MODEL_LOOKUP model find
@@ -1298,11 +1297,11 @@ describe("monitorModule", function () {
}); });
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should return monitors with basic query parameters", async function () { it("should return monitors with basic query parameters", async function() {
const mockMonitors = [ const mockMonitors = [
{ _id: "1", type: "http", toObject: () => ({ _id: "1", type: "http" }) }, { _id: "1", type: "http", toObject: () => ({ _id: "1", type: "http" }) },
{ _id: "2", type: "ping", toObject: () => ({ _id: "2", type: "ping" }) }, { _id: "2", type: "ping", toObject: () => ({ _id: "2", type: "ping" }) },
@@ -1335,7 +1334,7 @@ describe("monitorModule", function () {
expect(result).to.have.property("monitorCount", 2); expect(result).to.have.property("monitorCount", 2);
}); });
it("should return monitors with basic query parameters", async function () { it("should return monitors with basic query parameters", async function() {
const mockMonitors = [ const mockMonitors = [
{ _id: "1", type: "http", toObject: () => ({ _id: "1", type: "http" }) }, { _id: "1", type: "http", toObject: () => ({ _id: "1", type: "http" }) },
{ _id: "2", type: "ping", toObject: () => ({ _id: "2", type: "ping" }) }, { _id: "2", type: "ping", toObject: () => ({ _id: "2", type: "ping" }) },
@@ -1368,7 +1367,7 @@ describe("monitorModule", function () {
expect(result).to.have.property("monitorCount", 2); expect(result).to.have.property("monitorCount", 2);
}); });
it("should handle type filter with array input", async function () { it("should handle type filter with array input", async function() {
const req = { const req = {
params: { teamId: "team123" }, params: { teamId: "team123" },
query: { query: {
@@ -1393,7 +1392,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle text search filter", async function () { it("should handle text search filter", async function() {
const req = { const req = {
params: { teamId: "team123" }, params: { teamId: "team123" },
query: { query: {
@@ -1421,7 +1420,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle pagination parameters", async function () { it("should handle pagination parameters", async function() {
const req = { const req = {
params: { teamId: "team123" }, params: { teamId: "team123" },
query: { query: {
@@ -1446,7 +1445,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should handle sorting parameters", async function () { it("should handle sorting parameters", async function() {
const req = { const req = {
params: { teamId: "team123" }, params: { teamId: "team123" },
query: { query: {
@@ -1473,7 +1472,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should return early when limit is -1", async function () { it("should return early when limit is -1", async function() {
// Arrange // Arrange
const req = { const req = {
params: { teamId: "team123" }, params: { teamId: "team123" },
@@ -1507,7 +1506,7 @@ describe("monitorModule", function () {
}); });
}); });
it("should normalize checks when normalize parameter is provided", async function () { it("should normalize checks when normalize parameter is provided", async function() {
const req = { const req = {
params: { teamId: "team123" }, params: { teamId: "team123" },
query: { normalize: "true" }, query: { normalize: "true" },
@@ -1532,7 +1531,7 @@ describe("monitorModule", function () {
expect(result.monitors).to.have.lengthOf(2); expect(result.monitors).to.have.lengthOf(2);
}); });
it("should handle database errors", async function () { it("should handle database errors", async function() {
const req = { const req = {
params: { teamId: "team123" }, params: { teamId: "team123" },
query: {}, query: {},
@@ -1558,8 +1557,8 @@ describe("monitorModule", function () {
}); });
}); });
describe("createMonitor", function () { describe("createMonitor", function() {
it("should create a monitor without notifications", async function () { it("should create a monitor without notifications", async function() {
let monitorSaveStub = sinon.stub(Monitor.prototype, "save").resolves(); let monitorSaveStub = sinon.stub(Monitor.prototype, "save").resolves();
const req = { const req = {
@@ -1584,7 +1583,7 @@ describe("monitorModule", function () {
expect(result.url).to.equal(expectedMonitor.url); expect(result.url).to.equal(expectedMonitor.url);
}); });
it("should handle database errors", async function () { it("should handle database errors", async function() {
const req = { const req = {
body: { body: {
name: "Test Monitor", name: "Test Monitor",
@@ -1601,8 +1600,8 @@ describe("monitorModule", function () {
}); });
}); });
describe("deleteMonitor", function () { describe("deleteMonitor", function() {
it("should delete a monitor successfully", async function () { it("should delete a monitor successfully", async function() {
const monitorId = "123456789"; const monitorId = "123456789";
const mockMonitor = { const mockMonitor = {
_id: monitorId, _id: monitorId,
@@ -1622,11 +1621,10 @@ describe("monitorModule", function () {
sinon.assert.calledWith(monitorFindByIdAndDeleteStub, monitorId); sinon.assert.calledWith(monitorFindByIdAndDeleteStub, monitorId);
}); });
it("should throw error when monitor not found", async function () { it("should throw error when monitor not found", async function() {
const monitorId = "nonexistent123"; const monitorId = "nonexistent123";
const req = { const req = {
params: { monitorId }, params: { monitorId },
language: 'en',
}; };
monitorFindByIdAndDeleteStub.resolves(null); monitorFindByIdAndDeleteStub.resolves(null);
@@ -1635,13 +1633,13 @@ describe("monitorModule", function () {
await deleteMonitor(req); await deleteMonitor(req);
expect.fail("Should have thrown an error"); expect.fail("Should have thrown an error");
} catch (err) { } catch (err) {
expect(err.message).to.equal(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId, req.language)); expect(err.message).to.equal(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
expect(err.service).to.equal("monitorModule"); expect(err.service).to.equal("monitorModule");
expect(err.method).to.equal("deleteMonitor"); expect(err.method).to.equal("deleteMonitor");
} }
}); });
it("should handle database errors", async function () { it("should handle database errors", async function() {
const monitorId = "123456789"; const monitorId = "123456789";
const req = { const req = {
params: { monitorId }, params: { monitorId },
@@ -1661,8 +1659,8 @@ describe("monitorModule", function () {
}); });
}); });
describe("deleteAllMonitors", function () { describe("deleteAllMonitors", function() {
it("should delete all monitors for a team successfully", async function () { it("should delete all monitors for a team successfully", async function() {
const teamId = "team123"; const teamId = "team123";
const mockMonitors = [ const mockMonitors = [
{ _id: "1", name: "Monitor 1", teamId }, { _id: "1", name: "Monitor 1", teamId },
@@ -1682,7 +1680,7 @@ describe("monitorModule", function () {
sinon.assert.calledWith(monitorDeleteManyStub, { teamId }); sinon.assert.calledWith(monitorDeleteManyStub, { teamId });
}); });
it("should return empty array when no monitors found", async function () { it("should return empty array when no monitors found", async function() {
const teamId = "emptyTeam"; const teamId = "emptyTeam";
monitorFindStub.resolves([]); monitorFindStub.resolves([]);
@@ -1698,7 +1696,7 @@ describe("monitorModule", function () {
sinon.assert.calledWith(monitorDeleteManyStub, { teamId }); sinon.assert.calledWith(monitorDeleteManyStub, { teamId });
}); });
it("should handle database errors", async function () { it("should handle database errors", async function() {
const teamId = "team123"; const teamId = "team123";
const dbError = new Error("Database connection error"); const dbError = new Error("Database connection error");
monitorFindStub.rejects(dbError); monitorFindStub.rejects(dbError);
@@ -1712,7 +1710,7 @@ describe("monitorModule", function () {
} }
}); });
it("should handle deleteMany errors", async function () { it("should handle deleteMany errors", async function() {
const teamId = "team123"; const teamId = "team123";
monitorFindStub.resolves([{ _id: "1", name: "Monitor 1" }]); monitorFindStub.resolves([{ _id: "1", name: "Monitor 1" }]);
monitorDeleteManyStub.rejects(new Error("Delete operation failed")); monitorDeleteManyStub.rejects(new Error("Delete operation failed"));
@@ -1727,14 +1725,14 @@ describe("monitorModule", function () {
}); });
}); });
describe("deleteMonitorsByUserId", function () { describe("deleteMonitorsByUserId", function() {
beforeEach(function () { }); beforeEach(function() {});
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should delete all monitors for a user successfully", async function () { it("should delete all monitors for a user successfully", async function() {
// Arrange // Arrange
const userId = "user123"; const userId = "user123";
const mockResult = { const mockResult = {
@@ -1752,7 +1750,7 @@ describe("monitorModule", function () {
sinon.assert.calledWith(monitorDeleteManyStub, { userId: userId }); sinon.assert.calledWith(monitorDeleteManyStub, { userId: userId });
}); });
it("should return zero deletedCount when no monitors found", async function () { it("should return zero deletedCount when no monitors found", async function() {
// Arrange // Arrange
const userId = "nonexistentUser"; const userId = "nonexistentUser";
const mockResult = { const mockResult = {
@@ -1770,7 +1768,7 @@ describe("monitorModule", function () {
sinon.assert.calledWith(monitorDeleteManyStub, { userId: userId }); sinon.assert.calledWith(monitorDeleteManyStub, { userId: userId });
}); });
it("should handle database errors", async function () { it("should handle database errors", async function() {
// Arrange // Arrange
const userId = "user123"; const userId = "user123";
const dbError = new Error("Database connection error"); const dbError = new Error("Database connection error");
@@ -1788,8 +1786,8 @@ describe("monitorModule", function () {
}); });
}); });
describe("editMonitor", function () { describe("editMonitor", function() {
it("should edit a monitor successfully", async function () { it("should edit a monitor successfully", async function() {
// Arrange // Arrange
const candidateId = "monitor123"; const candidateId = "monitor123";
const candidateMonitor = { const candidateMonitor = {
@@ -1828,7 +1826,7 @@ describe("monitorModule", function () {
); );
}); });
it("should return null when monitor not found", async function () { it("should return null when monitor not found", async function() {
// Arrange // Arrange
const candidateId = "nonexistent123"; const candidateId = "nonexistent123";
const candidateMonitor = { const candidateMonitor = {
@@ -1850,7 +1848,7 @@ describe("monitorModule", function () {
); );
}); });
it("should remove notifications from update data", async function () { it("should remove notifications from update data", async function() {
// Arrange // Arrange
const candidateId = "monitor123"; const candidateId = "monitor123";
const candidateMonitor = { const candidateMonitor = {
@@ -1882,7 +1880,7 @@ describe("monitorModule", function () {
); );
}); });
it("should handle database errors", async function () { it("should handle database errors", async function() {
// Arrange // Arrange
const candidateId = "monitor123"; const candidateId = "monitor123";
const candidateMonitor = { const candidateMonitor = {
@@ -1904,8 +1902,8 @@ describe("monitorModule", function () {
}); });
}); });
describe("addDemoMonitors", function () { describe("addDemoMonitors", function() {
it("should add demo monitors successfully", async function () { it("should add demo monitors successfully", async function() {
// Arrange // Arrange
const userId = "user123"; const userId = "user123";
const teamId = "team123"; const teamId = "team123";
@@ -1914,7 +1912,7 @@ describe("monitorModule", function () {
expect(result).to.deep.equal([{ _id: "123" }]); expect(result).to.deep.equal([{ _id: "123" }]);
}); });
it("should handle database errors", async function () { it("should handle database errors", async function() {
const userId = "user123"; const userId = "user123";
const teamId = "team123"; const teamId = "team123";
+21 -23
View File
@@ -43,7 +43,7 @@ const createQueryChain = (finalResult, comparePasswordResult = false) => ({
save: sinon.stub().resolves(), save: sinon.stub().resolves(),
}); });
describe("recoveryModule", function () { describe("recoveryModule", function() {
let deleteManyStub, let deleteManyStub,
saveStub, saveStub,
findOneStub, findOneStub,
@@ -52,10 +52,9 @@ describe("recoveryModule", function () {
userFindOneStub; userFindOneStub;
let req, res; let req, res;
beforeEach(function () { beforeEach(function() {
req = { req = {
body: { email: "test@test.com" }, body: { email: "test@test.com" },
language: 'en',
}; };
deleteManyStub = sinon.stub(RecoveryToken, "deleteMany"); deleteManyStub = sinon.stub(RecoveryToken, "deleteMany");
saveStub = sinon.stub(RecoveryToken.prototype, "save"); saveStub = sinon.stub(RecoveryToken.prototype, "save");
@@ -65,19 +64,19 @@ describe("recoveryModule", function () {
userFindOneStub = sinon.stub().resolves(); userFindOneStub = sinon.stub().resolves();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
describe("requestRecoveryToken", function () { describe("requestRecoveryToken", function() {
it("should return a recovery token", async function () { it("should return a recovery token", async function() {
deleteManyStub.resolves(); deleteManyStub.resolves();
saveStub.resolves(mockRecoveryToken); saveStub.resolves(mockRecoveryToken);
const result = await requestRecoveryToken(req, res); const result = await requestRecoveryToken(req, res);
expect(result.email).to.equal(mockRecoveryToken.email); expect(result.email).to.equal(mockRecoveryToken.email);
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("Test error"); const err = new Error("Test error");
deleteManyStub.rejects(err); deleteManyStub.rejects(err);
try { try {
@@ -89,24 +88,24 @@ describe("recoveryModule", function () {
}); });
}); });
describe("validateRecoveryToken", function () { describe("validateRecoveryToken", function() {
it("should return a recovery token if found", async function () { it("should return a recovery token if found", async function() {
findOneStub.resolves(mockRecoveryToken); findOneStub.resolves(mockRecoveryToken);
const result = await validateRecoveryToken(req, res); const result = await validateRecoveryToken(req, res);
expect(result).to.deep.equal(mockRecoveryToken); expect(result).to.deep.equal(mockRecoveryToken);
}); });
it("should thrown an error if a token is not found", async function () { it("should thrown an error if a token is not found", async function() {
findOneStub.resolves(null); findOneStub.resolves(null);
try { try {
await validateRecoveryToken(req, res); await validateRecoveryToken(req, res);
} catch (error) { } catch (error) {
expect(error).to.exist; expect(error).to.exist;
expect(error.message).to.equal(errorMessages.DB_TOKEN_NOT_FOUND(req.language)); expect(error.message).to.equal(errorMessages.DB_TOKEN_NOT_FOUND);
} }
}); });
it("should handle DB errors", async function () { it("should handle DB errors", async function() {
const err = new Error("Test error"); const err = new Error("Test error");
findOneStub.rejects(err); findOneStub.rejects(err);
try { try {
@@ -118,41 +117,40 @@ describe("recoveryModule", function () {
}); });
}); });
describe("resetPassword", function () { describe("resetPassword", function() {
beforeEach(function () { beforeEach(function() {
req.body = { req.body = {
password: "test", password: "test",
newPassword: "test1", newPassword: "test1",
}; };
req.language = 'en';
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should thrown an error if a recovery token is not found", async function () { it("should thrown an error if a recovery token is not found", async function() {
findOneStub.resolves(null); findOneStub.resolves(null);
try { try {
await resetPassword(req, res); await resetPassword(req, res);
} catch (error) { } catch (error) {
expect(error).to.exist; expect(error).to.exist;
expect(error.message).to.equal(errorMessages.DB_TOKEN_NOT_FOUND(req.language)); expect(error.message).to.equal(errorMessages.DB_TOKEN_NOT_FOUND);
} }
}); });
it("should throw an error if a user is not found", async function () { it("should throw an error if a user is not found", async function() {
findOneStub.resolves(mockRecoveryToken); findOneStub.resolves(mockRecoveryToken);
userFindOneStub = sinon.stub(User, "findOne").resolves(null); userFindOneStub = sinon.stub(User, "findOne").resolves(null);
try { try {
await resetPassword(req, res); await resetPassword(req, res);
} catch (error) { } catch (error) {
expect(error).to.exist; expect(error).to.exist;
expect(error.message).to.equal(errorMessages.DB_USER_NOT_FOUND(req.language)); expect(error.message).to.equal(errorMessages.DB_USER_NOT_FOUND);
} }
}); });
it("should throw an error if the passwords match", async function () { it("should throw an error if the passwords match", async function() {
findOneStub.resolves(mockRecoveryToken); findOneStub.resolves(mockRecoveryToken);
saveStub.resolves(); saveStub.resolves();
userFindOneStub = sinon userFindOneStub = sinon
@@ -162,11 +160,11 @@ describe("recoveryModule", function () {
await resetPassword(req, res); await resetPassword(req, res);
} catch (error) { } catch (error) {
expect(error).to.exist; expect(error).to.exist;
expect(error.message).to.equal(errorMessages.DB_RESET_PASSWORD_BAD_MATCH(req.language)); expect(error.message).to.equal(errorMessages.DB_RESET_PASSWORD_BAD_MATCH);
} }
}); });
it("should return a user without password if successful", async function () { it("should return a user without password if successful", async function() {
findOneStub.resolves(mockRecoveryToken); findOneStub.resolves(mockRecoveryToken);
saveStub.resolves(); saveStub.resolves();
userFindOneStub = sinon userFindOneStub = sinon
+14 -15
View File
@@ -6,32 +6,31 @@ import {
import StatusPage from "../../db/models/StatusPage.js"; import StatusPage from "../../db/models/StatusPage.js";
import { errorMessages } from "../../utils/messages.js"; import { errorMessages } from "../../utils/messages.js";
describe("statusPageModule", function () { describe("statusPageModule", function() {
let statusPageFindOneStub, statusPageSaveStub, statusPageFindStub, mockLanguage; let statusPageFindOneStub, statusPageSaveStub, statusPageFindStub;
beforeEach(function () { beforeEach(function() {
mockLanguage = 'en';
statusPageSaveStub = sinon.stub(StatusPage.prototype, "save"); statusPageSaveStub = sinon.stub(StatusPage.prototype, "save");
statusPageFindOneStub = sinon.stub(StatusPage, "findOne"); statusPageFindOneStub = sinon.stub(StatusPage, "findOne");
statusPageFindStub = sinon.stub(StatusPage, "find"); statusPageFindStub = sinon.stub(StatusPage, "find");
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
describe("createStatusPage", function () { describe("createStatusPage", function() {
it("should throw an error if a non-unique url is provided", async function () { it("should throw an error if a non-unique url is provided", async function() {
statusPageFindOneStub.resolves(true); statusPageFindOneStub.resolves(true);
try { try {
await createStatusPage({ url: "test" }); await createStatusPage({ url: "test" });
} catch (error) { } catch (error) {
expect(error.status).to.equal(400); expect(error.status).to.equal(400);
expect(error.message).to.equal(errorMessages.STATUS_PAGE_URL_NOT_UNIQUE(mockLanguage)); expect(error.message).to.equal(errorMessages.STATUS_PAGE_URL_NOT_UNIQUE);
} }
}); });
it("should handle duplicate URL errors", async function () { it("should handle duplicate URL errors", async function() {
const err = new Error("test"); const err = new Error("test");
err.code = 11000; err.code = 11000;
statusPageSaveStub.rejects(err); statusPageSaveStub.rejects(err);
@@ -42,7 +41,7 @@ describe("statusPageModule", function () {
} }
}); });
it("should return a status page if a unique url is provided", async function () { it("should return a status page if a unique url is provided", async function() {
statusPageFindOneStub.resolves(null); statusPageFindOneStub.resolves(null);
statusPageFindStub.resolves([]); statusPageFindStub.resolves([]);
const mockStatusPage = { url: "test" }; const mockStatusPage = { url: "test" };
@@ -52,21 +51,21 @@ describe("statusPageModule", function () {
}); });
}); });
describe("getStatusPageByUrl", function () { describe("getStatusPageByUrl", function() {
it("should throw an error if a status page is not found", async function () { it("should throw an error if a status page is not found", async function() {
statusPageFindOneStub.resolves(null); statusPageFindOneStub.resolves(null);
try { try {
await getStatusPageByUrl("test"); await getStatusPageByUrl("test");
} catch (error) { } catch (error) {
expect(error.status).to.equal(404); expect(error.status).to.equal(404);
expect(error.message).to.equal(errorMessages.STATUS_PAGE_NOT_FOUND(mockLanguage)); expect(error.message).to.equal(errorMessages.STATUS_PAGE_NOT_FOUND);
} }
}); });
it("should return a status page if a status page is found", async function () { it("should return a status page if a status page is found", async function() {
const mockStatusPage = { url: "test" }; const mockStatusPage = { url: "test" };
statusPageFindOneStub.resolves(mockStatusPage); statusPageFindOneStub.resolves(mockStatusPage);
const statusPage = await getStatusPageByUrl(mockStatusPage.url, mockLanguage); const statusPage = await getStatusPageByUrl(mockStatusPage.url);
expect(statusPage).to.exist; expect(statusPage).to.exist;
expect(statusPage).to.deep.equal(mockStatusPage); expect(statusPage).to.deep.equal(mockStatusPage);
}); });
+36 -38
View File
@@ -27,9 +27,7 @@ const imageFile = {
image: 1, image: 1,
}; };
const mockLanguage = 'en'; describe("userModule", function() {
describe("userModule", function () {
let teamSaveStub, let teamSaveStub,
teamFindByIdAndDeleteStub, teamFindByIdAndDeleteStub,
userSaveStub, userSaveStub,
@@ -42,7 +40,7 @@ describe("userModule", function () {
generateAvatarImageStub, generateAvatarImageStub,
parseBooleanStub; parseBooleanStub;
beforeEach(function () { beforeEach(function() {
teamSaveStub = sinon.stub(TeamModel.prototype, "save"); teamSaveStub = sinon.stub(TeamModel.prototype, "save");
teamFindByIdAndDeleteStub = sinon.stub(TeamModel, "findByIdAndDelete"); teamFindByIdAndDeleteStub = sinon.stub(TeamModel, "findByIdAndDelete");
userSaveStub = sinon.stub(UserModel.prototype, "save"); userSaveStub = sinon.stub(UserModel.prototype, "save");
@@ -56,12 +54,12 @@ describe("userModule", function () {
parseBooleanStub = sinon.stub().returns(true); parseBooleanStub = sinon.stub().returns(true);
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
describe("insertUser", function () { describe("insertUser", function() {
it("should insert a regular user", async function () { it("should insert a regular user", async function() {
userSaveStub.resolves(mockUser); userSaveStub.resolves(mockUser);
userFindOneStub.returns({ userFindOneStub.returns({
select: sinon.stub().returns({ select: sinon.stub().returns({
@@ -72,7 +70,7 @@ describe("userModule", function () {
expect(result).to.deep.equal(mockUser); expect(result).to.deep.equal(mockUser);
}); });
it("should insert a superadmin user", async function () { it("should insert a superadmin user", async function() {
userSaveStub.resolves(mockSuperUser); userSaveStub.resolves(mockSuperUser);
userFindOneStub.returns({ userFindOneStub.returns({
select: sinon.stub().returns({ select: sinon.stub().returns({
@@ -83,7 +81,7 @@ describe("userModule", function () {
expect(result).to.deep.equal(mockSuperUser); expect(result).to.deep.equal(mockSuperUser);
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("test error"); const err = new Error("test error");
userSaveStub.rejects(err); userSaveStub.rejects(err);
try { try {
@@ -94,7 +92,7 @@ describe("userModule", function () {
} }
}); });
it("should handle a duplicate key error", async function () { it("should handle a duplicate key error", async function() {
const err = new Error("test error"); const err = new Error("test error");
err.code = 11000; err.code = 11000;
userSaveStub.rejects(err); userSaveStub.rejects(err);
@@ -107,8 +105,8 @@ describe("userModule", function () {
}); });
}); });
describe("getUserByEmail", function () { describe("getUserByEmail", function() {
it("should return a user", async function () { it("should return a user", async function() {
userFindOneStub.returns({ userFindOneStub.returns({
select: sinon.stub().resolves(mockUser), select: sinon.stub().resolves(mockUser),
}); });
@@ -117,23 +115,23 @@ describe("userModule", function () {
}); });
}); });
describe("getUserByEmail", function () { describe("getUserByEmail", function() {
it("throw an error if a user is not found", async function () { it("throw an error if a user is not found", async function() {
userFindOneStub.returns({ userFindOneStub.returns({
select: sinon.stub().resolves(null), select: sinon.stub().resolves(null),
}); });
try { try {
await getUserByEmail(mockUser.email); await getUserByEmail(mockUser.email);
} catch (error) { } catch (error) {
expect(error.message).to.equal(errorMessages.DB_USER_NOT_FOUND(mockLanguage)); expect(error.message).to.equal(errorMessages.DB_USER_NOT_FOUND);
} }
}); });
}); });
describe("updateUser", function () { describe("updateUser", function() {
let req, res; let req, res;
beforeEach(function () { beforeEach(function() {
req = { req = {
params: { params: {
userId: "testId", userId: "testId",
@@ -150,9 +148,9 @@ describe("userModule", function () {
res = {}; res = {};
}); });
afterEach(function () { }); afterEach(function() {});
it("should update a user", async function () { it("should update a user", async function() {
parseBooleanStub.returns(false); parseBooleanStub.returns(false);
userFindByIdAndUpdateStub.returns({ userFindByIdAndUpdateStub.returns({
select: sinon.stub().returns({ select: sinon.stub().returns({
@@ -168,7 +166,7 @@ describe("userModule", function () {
expect(result).to.deep.equal(mockUser); expect(result).to.deep.equal(mockUser);
}); });
it("should delete a user profile image", async function () { it("should delete a user profile image", async function() {
req.body.deleteProfileImage = "true"; req.body.deleteProfileImage = "true";
userFindByIdAndUpdateStub.returns({ userFindByIdAndUpdateStub.returns({
select: sinon.stub().returns({ select: sinon.stub().returns({
@@ -184,7 +182,7 @@ describe("userModule", function () {
expect(result).to.deep.equal(mockUser); expect(result).to.deep.equal(mockUser);
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("test error"); const err = new Error("test error");
userFindByIdAndUpdateStub.throws(err); userFindByIdAndUpdateStub.throws(err);
try { try {
@@ -196,23 +194,23 @@ describe("userModule", function () {
}); });
}); });
describe("deleteUser", function () { describe("deleteUser", function() {
it("should return a deleted user", async function () { it("should return a deleted user", async function() {
userFindByIdAndDeleteStub.resolves(mockUser); userFindByIdAndDeleteStub.resolves(mockUser);
const result = await deleteUser("testId"); const result = await deleteUser("testId");
expect(result).to.deep.equal(mockUser); expect(result).to.deep.equal(mockUser);
}); });
it("should throw an error if a user is not found", async function () { it("should throw an error if a user is not found", async function() {
try { try {
await deleteUser("testId"); await deleteUser("testId");
} catch (error) { } catch (error) {
expect(error).to.exist; expect(error).to.exist;
expect(error.message).to.equal(errorMessages.DB_USER_NOT_FOUND(mockLanguage)); expect(error.message).to.equal(errorMessages.DB_USER_NOT_FOUND);
} }
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("test error"); const err = new Error("test error");
userFindByIdAndDeleteStub.throws(err); userFindByIdAndDeleteStub.throws(err);
try { try {
@@ -224,14 +222,14 @@ describe("userModule", function () {
}); });
}); });
describe("deleteTeam", function () { describe("deleteTeam", function() {
it("should return true if team deleted", async function () { it("should return true if team deleted", async function() {
teamFindByIdAndDeleteStub.resolves(); teamFindByIdAndDeleteStub.resolves();
const result = await deleteTeam("testId"); const result = await deleteTeam("testId");
expect(result).to.equal(true); expect(result).to.equal(true);
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("test error"); const err = new Error("test error");
teamFindByIdAndDeleteStub.throws(err); teamFindByIdAndDeleteStub.throws(err);
try { try {
@@ -243,14 +241,14 @@ describe("userModule", function () {
}); });
}); });
describe("deleteAllOtherUsers", function () { describe("deleteAllOtherUsers", function() {
it("should return true if all other users deleted", async function () { it("should return true if all other users deleted", async function() {
userDeleteManyStub.resolves(true); userDeleteManyStub.resolves(true);
const result = await deleteAllOtherUsers(); const result = await deleteAllOtherUsers();
expect(result).to.equal(true); expect(result).to.equal(true);
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("test error"); const err = new Error("test error");
userDeleteManyStub.throws(err); userDeleteManyStub.throws(err);
try { try {
@@ -262,8 +260,8 @@ describe("userModule", function () {
}); });
}); });
describe("getAllUsers", function () { describe("getAllUsers", function() {
it("should return all users", async function () { it("should return all users", async function() {
userFindStub.returns({ userFindStub.returns({
select: sinon.stub().returns({ select: sinon.stub().returns({
select: sinon.stub().resolves([mockUser]), select: sinon.stub().resolves([mockUser]),
@@ -273,7 +271,7 @@ describe("userModule", function () {
expect(result).to.deep.equal([mockUser]); expect(result).to.deep.equal([mockUser]);
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("test error"); const err = new Error("test error");
userFindStub.throws(err); userFindStub.throws(err);
try { try {
@@ -285,14 +283,14 @@ describe("userModule", function () {
}); });
}); });
describe("logoutUser", function () { describe("logoutUser", function() {
it("should return true if user logged out", async function () { it("should return true if user logged out", async function() {
userUpdateOneStub.resolves(true); userUpdateOneStub.resolves(true);
const result = await logoutUser("testId"); const result = await logoutUser("testId");
expect(result).to.equal(true); expect(result).to.equal(true);
}); });
it("should handle an error", async function () { it("should handle an error", async function() {
const err = new Error("test error"); const err = new Error("test error");
userUpdateOneStub.throws(err); userUpdateOneStub.throws(err);
try { try {
+46 -46
View File
@@ -3,10 +3,10 @@ import NetworkService from "../../service/networkService.js";
import { expect } from "chai"; import { expect } from "chai";
import http from "http"; import http from "http";
import { errorMessages } from "../../utils/messages.js"; import { errorMessages } from "../../utils/messages.js";
describe("Network Service", function () { describe("Network Service", function() {
let axios, ping, Docker, logger, networkService; let axios, ping, Docker, logger, networkService;
beforeEach(function () { beforeEach(function() {
axios = { axios = {
get: sinon.stub().resolves({ get: sinon.stub().resolves({
data: { foo: "bar" }, data: { foo: "bar" },
@@ -35,22 +35,22 @@ describe("Network Service", function () {
networkService = new NetworkService(axios, ping, logger, http, Docker); networkService = new NetworkService(axios, ping, logger, http, Docker);
}); });
describe("constructor", function () { describe("constructor", function() {
it("should create a new NetworkService instance", function () { it("should create a new NetworkService instance", function() {
const networkService = new NetworkService(); const networkService = new NetworkService();
expect(networkService).to.be.an.instanceOf(NetworkService); expect(networkService).to.be.an.instanceOf(NetworkService);
}); });
}); });
describe("timeRequest", function () { describe("timeRequest", function() {
it("should time an asynchronous operation", async function () { it("should time an asynchronous operation", async function() {
const operation = sinon.stub().resolves("success"); const operation = sinon.stub().resolves("success");
const { response, responseTime } = await networkService.timeRequest(operation); const { response, responseTime } = await networkService.timeRequest(operation);
expect(response).to.equal("success"); expect(response).to.equal("success");
expect(responseTime).to.be.a("number"); expect(responseTime).to.be.a("number");
}); });
it("should handle errors if operation throws error", async function () { it("should handle errors if operation throws error", async function() {
const error = new Error("Test error"); const error = new Error("Test error");
const operation = sinon.stub().throws(error); const operation = sinon.stub().throws(error);
const { response, responseTime } = await networkService.timeRequest(operation); const { response, responseTime } = await networkService.timeRequest(operation);
@@ -60,8 +60,8 @@ describe("Network Service", function () {
}); });
}); });
describe("requestPing", function () { describe("requestPing", function() {
it("should return a response object if ping successful", async function () { it("should return a response object if ping successful", async function() {
const pingResult = await networkService.requestPing({ const pingResult = await networkService.requestPing({
data: { url: "http://test.com", _id: "123" }, data: { url: "http://test.com", _id: "123" },
}); });
@@ -71,7 +71,7 @@ describe("Network Service", function () {
expect(pingResult.status).to.be.true; expect(pingResult.status).to.be.true;
}); });
it("should return a response object if ping unsuccessful", async function () { it("should return a response object if ping unsuccessful", async function() {
const error = new Error("Test error"); const error = new Error("Test error");
networkService.timeRequest = sinon networkService.timeRequest = sinon
.stub() .stub()
@@ -86,7 +86,7 @@ describe("Network Service", function () {
expect(pingResult.code).to.equal(networkService.PING_ERROR); expect(pingResult.code).to.equal(networkService.PING_ERROR);
}); });
it("should throw an error if ping cannot resolve", async function () { it("should throw an error if ping cannot resolve", async function() {
const error = new Error("test error"); const error = new Error("test error");
networkService.timeRequest = sinon.stub().throws(error); networkService.timeRequest = sinon.stub().throws(error);
try { try {
@@ -100,8 +100,8 @@ describe("Network Service", function () {
}); });
}); });
describe("requestHttp", function () { describe("requestHttp", function() {
it("should return a response object if http successful", async function () { it("should return a response object if http successful", async function() {
const job = { data: { url: "http://test.com", _id: "123", type: "http" } }; const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
const httpResult = await networkService.requestHttp(job); const httpResult = await networkService.requestHttp(job);
expect(httpResult.monitorId).to.equal("123"); expect(httpResult.monitorId).to.equal("123");
@@ -110,7 +110,7 @@ describe("Network Service", function () {
expect(httpResult.status).to.be.true; expect(httpResult.status).to.be.true;
}); });
it("should return a response object if http unsuccessful", async function () { it("should return a response object if http unsuccessful", async function() {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = { status: 404 }; error.response = { status: 404 };
networkService.timeRequest = sinon networkService.timeRequest = sinon
@@ -125,7 +125,7 @@ describe("Network Service", function () {
expect(httpResult.code).to.equal(404); expect(httpResult.code).to.equal(404);
}); });
it("should return a response object if http unsuccessful with unknown code", async function () { it("should return a response object if http unsuccessful with unknown code", async function() {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = {}; error.response = {};
networkService.timeRequest = sinon networkService.timeRequest = sinon
@@ -140,7 +140,7 @@ describe("Network Service", function () {
expect(httpResult.code).to.equal(networkService.NETWORK_ERROR); expect(httpResult.code).to.equal(networkService.NETWORK_ERROR);
}); });
it("should throw an error if an error occurs", async function () { it("should throw an error if an error occurs", async function() {
const error = new Error("test error"); const error = new Error("test error");
networkService.timeRequest = sinon.stub().throws(error); networkService.timeRequest = sinon.stub().throws(error);
try { try {
@@ -154,8 +154,8 @@ describe("Network Service", function () {
}); });
}); });
describe("requestPagespeed", function () { describe("requestPagespeed", function() {
it("should return a response object if pagespeed successful", async function () { it("should return a response object if pagespeed successful", async function() {
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } }; const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
const pagespeedResult = await networkService.requestPagespeed(job); const pagespeedResult = await networkService.requestPagespeed(job);
expect(pagespeedResult.monitorId).to.equal("123"); expect(pagespeedResult.monitorId).to.equal("123");
@@ -164,7 +164,7 @@ describe("Network Service", function () {
expect(pagespeedResult.status).to.be.true; expect(pagespeedResult.status).to.be.true;
}); });
it("should return a response object if pagespeed unsuccessful", async function () { it("should return a response object if pagespeed unsuccessful", async function() {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = { status: 404 }; error.response = { status: 404 };
networkService.timeRequest = sinon networkService.timeRequest = sinon
@@ -179,7 +179,7 @@ describe("Network Service", function () {
expect(pagespeedResult.code).to.equal(404); expect(pagespeedResult.code).to.equal(404);
}); });
it("should return a response object if pagespeed unsuccessful with an unknown code", async function () { it("should return a response object if pagespeed unsuccessful with an unknown code", async function() {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = {}; error.response = {};
networkService.timeRequest = sinon networkService.timeRequest = sinon
@@ -194,7 +194,7 @@ describe("Network Service", function () {
expect(pagespeedResult.code).to.equal(networkService.NETWORK_ERROR); expect(pagespeedResult.code).to.equal(networkService.NETWORK_ERROR);
}); });
it("should throw an error if pagespeed cannot resolve", async function () { it("should throw an error if pagespeed cannot resolve", async function() {
const error = new Error("test error"); const error = new Error("test error");
networkService.timeRequest = sinon.stub().throws(error); networkService.timeRequest = sinon.stub().throws(error);
try { try {
@@ -208,8 +208,8 @@ describe("Network Service", function () {
}); });
}); });
describe("requestHardware", function () { describe("requestHardware", function() {
it("should return a response object if hardware successful", async function () { it("should return a response object if hardware successful", async function() {
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } }; const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
const httpResult = await networkService.requestHardware(job); const httpResult = await networkService.requestHardware(job);
expect(httpResult.monitorId).to.equal("123"); expect(httpResult.monitorId).to.equal("123");
@@ -218,7 +218,7 @@ describe("Network Service", function () {
expect(httpResult.status).to.be.true; expect(httpResult.status).to.be.true;
}); });
it("should return a response object if hardware successful and job has a secret", async function () { it("should return a response object if hardware successful and job has a secret", async function() {
const job = { const job = {
data: { data: {
url: "http://test.com", url: "http://test.com",
@@ -234,7 +234,7 @@ describe("Network Service", function () {
expect(httpResult.status).to.be.true; expect(httpResult.status).to.be.true;
}); });
it("should return a response object if hardware unsuccessful", async function () { it("should return a response object if hardware unsuccessful", async function() {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = { status: 404 }; error.response = { status: 404 };
networkService.timeRequest = sinon networkService.timeRequest = sinon
@@ -249,7 +249,7 @@ describe("Network Service", function () {
expect(httpResult.code).to.equal(404); expect(httpResult.code).to.equal(404);
}); });
it("should return a response object if hardware unsuccessful with unknown code", async function () { it("should return a response object if hardware unsuccessful with unknown code", async function() {
const error = new Error("Test error"); const error = new Error("Test error");
error.response = {}; error.response = {};
networkService.timeRequest = sinon networkService.timeRequest = sinon
@@ -264,7 +264,7 @@ describe("Network Service", function () {
expect(httpResult.code).to.equal(networkService.NETWORK_ERROR); expect(httpResult.code).to.equal(networkService.NETWORK_ERROR);
}); });
it("should throw an error if hardware cannot resolve", async function () { it("should throw an error if hardware cannot resolve", async function() {
const error = new Error("test error"); const error = new Error("test error");
networkService.timeRequest = sinon.stub().throws(error); networkService.timeRequest = sinon.stub().throws(error);
try { try {
@@ -278,8 +278,8 @@ describe("Network Service", function () {
}); });
}); });
describe("requestDocker", function () { describe("requestDocker", function() {
it("should return a response object if docker successful", async function () { it("should return a response object if docker successful", async function() {
const job = { data: { url: "http://test.com", _id: "123", type: "docker" } }; const job = { data: { url: "http://test.com", _id: "123", type: "docker" } };
const dockerResult = await networkService.requestDocker(job); const dockerResult = await networkService.requestDocker(job);
expect(dockerResult.monitorId).to.equal("123"); expect(dockerResult.monitorId).to.equal("123");
@@ -288,7 +288,7 @@ describe("Network Service", function () {
expect(dockerResult.status).to.be.true; expect(dockerResult.status).to.be.true;
}); });
it("should return a response object with status false if container not running", async function () { it("should return a response object with status false if container not running", async function() {
Docker = class { Docker = class {
listContainers = sinon.stub().resolves([ listContainers = sinon.stub().resolves([
{ {
@@ -307,7 +307,7 @@ describe("Network Service", function () {
expect(dockerResult.code).to.equal(200); expect(dockerResult.code).to.equal(200);
}); });
it("should handle an error when fetching the container", async function () { it("should handle an error when fetching the container", async function() {
Docker = class { Docker = class {
listContainers = sinon.stub().resolves([ listContainers = sinon.stub().resolves([
{ {
@@ -326,7 +326,7 @@ describe("Network Service", function () {
expect(dockerResult.code).to.equal(networkService.NETWORK_ERROR); expect(dockerResult.code).to.equal(networkService.NETWORK_ERROR);
}); });
it("should throw an error if operations fail", async function () { it("should throw an error if operations fail", async function() {
Docker = class { Docker = class {
listContainers = sinon.stub().resolves([ listContainers = sinon.stub().resolves([
{ {
@@ -345,7 +345,7 @@ describe("Network Service", function () {
} }
}); });
it("should throw an error if no matching images found", async function () { it("should throw an error if no matching images found", async function() {
Docker = class { Docker = class {
listContainers = sinon.stub().resolves([]); listContainers = sinon.stub().resolves([]);
getContainer = sinon.stub().throws(new Error("test error")); getContainer = sinon.stub().throws(new Error("test error"));
@@ -355,13 +355,13 @@ describe("Network Service", function () {
try { try {
await networkService.requestDocker(job); await networkService.requestDocker(job);
} catch (error) { } catch (error) {
expect(error.message).to.equal(errorMessages.DOCKER_NOT_FOUND(mockLanguage)); expect(error.message).to.equal(errorMessages.DOCKER_NOT_FOUND);
} }
}); });
}); });
describe("getStatus", function () { describe("getStatus", function() {
beforeEach(function () { beforeEach(function() {
networkService.requestPing = sinon.stub(); networkService.requestPing = sinon.stub();
networkService.requestHttp = sinon.stub(); networkService.requestHttp = sinon.stub();
networkService.requestPagespeed = sinon.stub(); networkService.requestPagespeed = sinon.stub();
@@ -369,11 +369,11 @@ describe("Network Service", function () {
networkService.requestDocker = sinon.stub(); networkService.requestDocker = sinon.stub();
}); });
afterEach(function () { afterEach(function() {
sinon.restore(); sinon.restore();
}); });
it("should call requestPing if type is ping", async function () { it("should call requestPing if type is ping", async function() {
await networkService.getStatus({ data: { type: "ping" } }); await networkService.getStatus({ data: { type: "ping" } });
expect(networkService.requestPing.calledOnce).to.be.true; expect(networkService.requestPing.calledOnce).to.be.true;
expect(networkService.requestDocker.notCalled).to.be.true; expect(networkService.requestDocker.notCalled).to.be.true;
@@ -381,7 +381,7 @@ describe("Network Service", function () {
expect(networkService.requestPagespeed.notCalled).to.be.true; expect(networkService.requestPagespeed.notCalled).to.be.true;
}); });
it("should call requestHttp if type is http", async function () { it("should call requestHttp if type is http", async function() {
await networkService.getStatus({ data: { type: "http" } }); await networkService.getStatus({ data: { type: "http" } });
expect(networkService.requestPing.notCalled).to.be.true; expect(networkService.requestPing.notCalled).to.be.true;
expect(networkService.requestDocker.notCalled).to.be.true; expect(networkService.requestDocker.notCalled).to.be.true;
@@ -389,7 +389,7 @@ describe("Network Service", function () {
expect(networkService.requestPagespeed.notCalled).to.be.true; expect(networkService.requestPagespeed.notCalled).to.be.true;
}); });
it("should call requestPagespeed if type is pagespeed", async function () { it("should call requestPagespeed if type is pagespeed", async function() {
await networkService.getStatus({ data: { type: "pagespeed" } }); await networkService.getStatus({ data: { type: "pagespeed" } });
expect(networkService.requestPing.notCalled).to.be.true; expect(networkService.requestPing.notCalled).to.be.true;
expect(networkService.requestDocker.notCalled).to.be.true; expect(networkService.requestDocker.notCalled).to.be.true;
@@ -397,7 +397,7 @@ describe("Network Service", function () {
expect(networkService.requestPagespeed.calledOnce).to.be.true; expect(networkService.requestPagespeed.calledOnce).to.be.true;
}); });
it("should call requestHardware if type is hardware", async function () { it("should call requestHardware if type is hardware", async function() {
await networkService.getStatus({ data: { type: "hardware" } }); await networkService.getStatus({ data: { type: "hardware" } });
expect(networkService.requestHardware.calledOnce).to.be.true; expect(networkService.requestHardware.calledOnce).to.be.true;
expect(networkService.requestDocker.notCalled).to.be.true; expect(networkService.requestDocker.notCalled).to.be.true;
@@ -405,7 +405,7 @@ describe("Network Service", function () {
expect(networkService.requestPagespeed.notCalled).to.be.true; expect(networkService.requestPagespeed.notCalled).to.be.true;
}); });
it("should call requestDocker if type is Docker", async function () { it("should call requestDocker if type is Docker", async function() {
await networkService.getStatus({ data: { type: "docker" } }); await networkService.getStatus({ data: { type: "docker" } });
expect(networkService.requestDocker.calledOnce).to.be.true; expect(networkService.requestDocker.calledOnce).to.be.true;
expect(networkService.requestHardware.notCalled).to.be.true; expect(networkService.requestHardware.notCalled).to.be.true;
@@ -413,7 +413,7 @@ describe("Network Service", function () {
expect(networkService.requestPagespeed.notCalled).to.be.true; expect(networkService.requestPagespeed.notCalled).to.be.true;
}); });
it("should throw an error if an unknown type is provided", async function () { it("should throw an error if an unknown type is provided", async function() {
try { try {
await networkService.getStatus({ data: { type: "unknown" } }); await networkService.getStatus({ data: { type: "unknown" } });
} catch (error) { } catch (error) {
@@ -423,7 +423,7 @@ describe("Network Service", function () {
} }
}); });
it("should throw an error if job type is undefined", async function () { it("should throw an error if job type is undefined", async function() {
try { try {
await networkService.getStatus({ data: { type: undefined } }); await networkService.getStatus({ data: { type: undefined } });
} catch (error) { } catch (error) {
@@ -433,7 +433,7 @@ describe("Network Service", function () {
} }
}); });
it("should throw an error if job is empty", async function () { it("should throw an error if job is empty", async function() {
try { try {
await networkService.getStatus({}); await networkService.getStatus({});
} catch (error) { } catch (error) {
@@ -442,7 +442,7 @@ describe("Network Service", function () {
} }
}); });
it("should throw an error if job is null", async function () { it("should throw an error if job is null", async function() {
try { try {
await networkService.getStatus(null); await networkService.getStatus(null);
} catch (error) { } catch (error) {
+8 -10
View File
@@ -1,25 +1,23 @@
import { errorMessages, successMessages } from "../../utils/messages.js"; import { errorMessages, successMessages } from "../../utils/messages.js";
describe("Messages", function () { describe("Messages", function() {
describe("messages - errorMessages", function () { describe("messages - errorMessages", function() {
it("should have a DB_FIND_MONITOR_BY_ID function", function () { it("should have a DB_FIND_MONITOR_BY_ID function", function() {
const monitorId = "12345"; const monitorId = "12345";
const mockLanguage = 'en'; expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)).to.equal(
expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId, mockLanguage)).to.equal(
`Monitor with id ${monitorId} not found` `Monitor with id ${monitorId} not found`
); );
}); });
it("should have a DB_DELETE_CHECKS function", function () { it("should have a DB_DELETE_CHECKS function", function() {
const monitorId = "12345"; const monitorId = "12345";
const mockLanguage = 'en'; expect(errorMessages.DB_DELETE_CHECKS(monitorId)).to.equal(
expect(errorMessages.DB_DELETE_CHECKS(monitorId, mockLanguage)).to.equal(
`No checks found for monitor with id ${monitorId}` `No checks found for monitor with id ${monitorId}`
); );
}); });
}); });
describe("messages - successMessages", function () { describe("messages - successMessages", function() {
it("should have a MONITOR_GET_BY_USER_ID function", function () { it("should have a MONITOR_GET_BY_USER_ID function", function() {
const userId = "12345"; const userId = "12345";
expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal( expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal(
`Got monitor for ${userId} successfully"` `Got monitor for ${userId} successfully"`