fix: revert tests

This commit is contained in:
cihatata
2025-01-30 01:11:55 +03:00
committed by cihat
parent dea8c4fdd8
commit 08933743f1
12 changed files with 617 additions and 645 deletions

View File

@@ -18,16 +18,14 @@ import { getTokenFromHeaders, tokenType } from "../../utils/utils.js";
import logger from "../../utils/logger.js";
import e from "cors";
const mockLanguage = 'en';
describe("Auth Controller - issueToken", function () {
describe("Auth Controller - issueToken", function() {
let stub;
afterEach(function () {
afterEach(function() {
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");
stub = sinon.stub(jwt, "sign").throws(error);
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 appSettings = { jwtSecret: "my_secret" };
const expectedToken = "mockToken";
@@ -47,7 +45,7 @@ describe("Auth Controller - issueToken", function () {
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 appSettings = { jwtSecret: "my_secret", jwtTTL: "1s" };
const expectedToken = "mockToken";
@@ -57,7 +55,7 @@ describe("Auth Controller - issueToken", function () {
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 appSettings = { refreshTokenSecret: "my_refresh_secret" };
const expectedToken = "mockRefreshToken";
@@ -67,7 +65,7 @@ describe("Auth Controller - issueToken", function () {
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 appSettings = {
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;
beforeEach(function () {
beforeEach(function() {
req = {
body: {
firstName: "firstname",
@@ -120,25 +118,25 @@ describe("Auth Controller - registerUser", function () {
sinon.stub(logger, "error");
});
afterEach(function () {
afterEach(function() {
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 = {};
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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.getInviteTokenAndDelete.throws(new Error("getInviteTokenAndDelete error"));
await registerUser(req, res, next);
@@ -146,7 +144,7 @@ describe("Auth Controller - registerUser", function () {
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.updateAppSettings.throws(new Error("updateAppSettings error"));
await registerUser(req, res, next);
@@ -154,7 +152,7 @@ describe("Auth Controller - registerUser", function () {
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.updateAppSettings.resolves();
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");
});
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.updateAppSettings.resolves();
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");
});
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.updateAppSettings.resolves();
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");
});
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" };
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
@@ -204,14 +202,14 @@ describe("Auth Controller - registerUser", function () {
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_CREATE_USER(mockLanguage),
msg: successMessages.AUTH_CREATE_USER,
data: { user, token: sinon.match.string, refreshToken: sinon.match.string },
})
).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" };
req.db.checkSuperadmin.resolves(true);
req.db.updateAppSettings.resolves();
@@ -226,7 +224,7 @@ describe("Auth Controller - registerUser", function () {
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_CREATE_USER(mockLanguage),
msg: successMessages.AUTH_CREATE_USER,
data: { user, token: sinon.match.string, refreshToken: sinon.match.string },
})
).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;
beforeEach(function () {
beforeEach(function() {
req = {
body: { email: "test@example.com", password: "Password123!" },
db: {
getUserByEmail: sinon.stub(),
},
language: 'en',
settingsService: {
getSettings: sinon.stub().resolves({
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 = {};
await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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);
user.comparePassword.resolves(true);
await loginUser(req, res, next);
@@ -286,7 +283,7 @@ describe("Auth Controller - loginUser", function () {
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_LOGIN_USER(mockLanguage),
msg: successMessages.AUTH_LOGIN_USER,
data: {
user: {
email: "test@example.com",
@@ -300,7 +297,7 @@ describe("Auth Controller - loginUser", function () {
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 = {
email: "test@test.com",
password: "Password123!",
@@ -310,15 +307,15 @@ describe("Auth Controller - loginUser", function () {
await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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;
beforeEach(function () {
beforeEach(function() {
req = {
headers: {
"x-refresh-token": "valid_refresh_token",
@@ -342,39 +339,39 @@ describe("Auth Controller - refreshAuthToken", function () {
sinon.replace({ issueToken }, "issueToken", issueTokenStub);
});
afterEach(function () {
afterEach(function() {
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"];
await refreshAuthToken(req, res, next);
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);
});
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"));
await refreshAuthToken(req, res, next);
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);
});
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");
error.name = "TokenExpiredError";
jwt.verify.yields(error);
await refreshAuthToken(req, res, next);
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);
});
it("should reject if settingsService.getSettings fails", async function () {
it("should reject if settingsService.getSettings fails", async function() {
req.settingsService.getSettings.rejects(
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");
});
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" };
jwt.verify.callsFake(() => {
return decodedPayload;
@@ -395,7 +392,7 @@ describe("Auth Controller - refreshAuthToken", function () {
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_TOKEN_REFRESHED(mockLanguage),
msg: successMessages.AUTH_TOKEN_REFRESHED,
data: {
user: decodedPayload,
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;
beforeEach(function () {
beforeEach(function() {
req = {
params: { userId: "123" },
body: { password: "Password1!", newPassword: "Password2!" },
@@ -431,40 +428,40 @@ describe("Auth Controller - editUser", function () {
stub = sinon.stub(jwt, "verify").returns({ email: "test@example.com" });
});
afterEach(function () {
afterEach(function() {
sinon.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 = {};
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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 };
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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" };
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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({
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");
});
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({
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].status).to.equal(401);
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 = {
comparePassword: sinon.stub().resolves(true),
};
@@ -500,14 +497,14 @@ describe("Auth Controller - editUser", function () {
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_UPDATE_USER(mockLanguage),
msg: successMessages.AUTH_UPDATE_USER,
data: { email: "test@example.com" },
})
).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.newPassword = undefined;
req.db.getUserByEmail.resolves(user);
@@ -518,14 +515,14 @@ describe("Auth Controller - editUser", function () {
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_UPDATE_USER(mockLanguage),
msg: successMessages.AUTH_UPDATE_USER,
data: { email: "test@example.com" },
})
).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" };
const user = {
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;
beforeEach(function () {
beforeEach(function() {
req = {
db: {
checkSuperadmin: sinon.stub(),
@@ -555,35 +552,35 @@ describe("Auth Controller - checkSuperadminExists", function () {
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"));
await checkSuperadminExists(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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);
await checkSuperadminExists(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_SUPERADMIN_EXISTS(mockLanguage),
msg: successMessages.AUTH_SUPERADMIN_EXISTS,
data: true,
})
).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);
await checkSuperadminExists(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_SUPERADMIN_EXISTS(mockLanguage),
msg: successMessages.AUTH_SUPERADMIN_EXISTS,
data: false,
})
).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;
beforeEach(function () {
beforeEach(function() {
req = {
body: { email: "test@test.com" },
db: {
@@ -615,21 +612,21 @@ describe("Auth Controller - requestRecovery", function () {
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 = {};
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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);
await requestRecovery(req, res, next);
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 = {};
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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 recoveryToken = { token: "recovery-token" };
const msgId = "message-id";
@@ -671,7 +668,7 @@ describe("Auth Controller - requestRecovery", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN(mockLanguage),
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
data: msgId,
})
).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;
beforeEach(function () {
beforeEach(function() {
req = {
body: { recoveryToken: "recovery-token" },
db: {
@@ -696,38 +693,38 @@ describe("Auth Controller - validateRecovery", function () {
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 = {};
await validateRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await validateRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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();
await validateRecovery(req, res, next);
expect(res.status.calledOnceWith(200)).to.be.true;
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN(mockLanguage),
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
})
).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;
beforeEach(function () {
beforeEach(function() {
req = {
body: {
recoveryToken: "recovery-token",
@@ -752,14 +749,14 @@ describe("Auth Controller - resetPassword", function () {
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" };
await resetPassword(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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");
newPasswordValidation.validateAsync.resolves();
req.db.resetPassword.rejects(error);
@@ -768,7 +765,7 @@ describe("Auth Controller - resetPassword", function () {
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 appSettings = { jwtSecret: "my_secret" };
const token = "token";
@@ -785,7 +782,7 @@ describe("Auth Controller - resetPassword", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.AUTH_RESET_PASSWORD(mockLanguage),
msg: successMessages.AUTH_RESET_PASSWORD,
data: { user: sinon.match.object, token: sinon.match.string },
})
).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;
beforeEach(function () {
beforeEach(function() {
req = {
headers: {
authorization: "Bearer token",
@@ -828,24 +825,24 @@ describe("Auth Controller - deleteUser", function () {
handleError = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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" });
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);
expect(req.db.getUserByEmail.calledOnceWith("test@example.com")).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.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 = {
_id: "user_id",
email: "test@example.com",
@@ -879,13 +876,13 @@ describe("Auth Controller - deleteUser", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.AUTH_DELETE_USER(mockLanguage),
msg: successMessages.AUTH_DELETE_USER,
})
).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 = {
_id: "user_id",
email: "test@example.com",
@@ -909,13 +906,13 @@ describe("Auth Controller - deleteUser", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.AUTH_DELETE_USER(mockLanguage),
msg: successMessages.AUTH_DELETE_USER,
})
).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 SERVICE_NAME = "AuthController";
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;
beforeEach(function () {
beforeEach(function() {
req = {
db: {
getAllUsers: sinon.stub(),
@@ -944,11 +941,11 @@ describe("Auth Controller - getAllUsers", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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" }];
req.db.getAllUsers.resolves(allUsers);
@@ -966,7 +963,7 @@ describe("Auth Controller - getAllUsers", function () {
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");
req.db.getAllUsers.rejects(error);
await getAllUsers(req, res, next);

View File

@@ -9,12 +9,11 @@ import {
import jwt from "jsonwebtoken";
import { errorMessages, successMessages } from "../../utils/messages.js";
import sinon from "sinon";
describe("Check Controller - createCheck", function () {
describe("Check Controller - createCheck", function() {
let req, res, next, handleError;
beforeEach(function () {
beforeEach(function() {
req = {
language: 'en',
params: {},
body: {},
db: {
@@ -29,17 +28,17 @@ describe("Check Controller - createCheck", function () {
handleError = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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);
expect(next.firstCall.args[0]).to.be.an("error");
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 = {
monitorId: "monitorId",
};
@@ -48,7 +47,7 @@ describe("Check Controller - createCheck", function () {
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: "monitorId",
};
@@ -64,7 +63,7 @@ describe("Check Controller - createCheck", function () {
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 = {
monitorId: "monitorId",
};
@@ -81,7 +80,7 @@ describe("Check Controller - createCheck", function () {
expect(
res.json.calledWith({
success: true,
msg: successMessages.CHECK_CREATE(req.language),
msg: successMessages.CHECK_CREATE,
data: { id: "123" },
})
).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;
beforeEach(function () {
beforeEach(function() {
req = {
params: {},
query: {},
@@ -108,17 +107,17 @@ describe("Check Controller - getChecks", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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);
expect(next.firstCall.args[0]).to.be.an("error");
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 = {
monitorId: "monitorId",
};
@@ -129,14 +128,14 @@ describe("Check Controller - getChecks", function () {
expect(
res.json.calledWith({
success: true,
msg: successMessages.CHECK_GET(req.language),
msg: successMessages.CHECK_GET,
data: { checksCount: 1, checks: [{ id: "123" }] },
})
).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 = {
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;
beforeEach(function () {
beforeEach(function() {
req = {
params: {},
query: {},
@@ -164,17 +163,17 @@ describe("Check Controller - getTeamChecks", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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);
expect(next.firstCall.args[0]).to.be.an("error");
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" };
const checkData = [{ id: 1, name: "Check 1" }];
req.db.getTeamChecks.resolves(checkData);
@@ -185,13 +184,13 @@ describe("Check Controller - getTeamChecks", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.CHECK_GET(req.language),
msg: successMessages.CHECK_GET,
data: checkData,
})
).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.db.getTeamChecks.rejects(new Error("Retrieval Error"));
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;
beforeEach(function () {
beforeEach(function() {
req = {
params: {},
db: {
@@ -219,17 +218,17 @@ describe("Check Controller - deleteChecks", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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);
expect(next.firstCall.args[0]).to.be.an("error");
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.db.deleteChecks.rejects(new Error("Deletion Error"));
await deleteChecks(req, res, next);
@@ -239,7 +238,7 @@ describe("Check Controller - deleteChecks", function () {
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.db.deleteChecks.resolves(1);
await deleteChecks(req, res, next);
@@ -248,17 +247,17 @@ describe("Check Controller - deleteChecks", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.CHECK_DELETE(req.language),
msg: successMessages.CHECK_DELETE,
data: { deletedCount: 1 },
})
).to.be.true;
});
});
describe("Check Controller - deleteChecksByTeamId", function () {
describe("Check Controller - deleteChecksByTeamId", function() {
let req, res, next;
beforeEach(function () {
beforeEach(function() {
req = {
params: {},
db: {
@@ -272,17 +271,17 @@ describe("Check Controller - deleteChecksByTeamId", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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);
expect(next.firstCall.args[0]).to.be.an("error");
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.db.deleteChecksByTeamId.rejects(new Error("Deletion Error"));
await deleteChecksByTeamId(req, res, next);
@@ -292,7 +291,7 @@ describe("Check Controller - deleteChecksByTeamId", function () {
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.db.deleteChecksByTeamId.resolves(1);
await deleteChecksByTeamId(req, res, next);
@@ -301,17 +300,17 @@ describe("Check Controller - deleteChecksByTeamId", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.CHECK_DELETE(req.language),
msg: successMessages.CHECK_DELETE,
data: { deletedCount: 1 },
})
).to.be.true;
});
});
describe("Check Controller - updateCheckTTL", function () {
describe("Check Controller - updateCheckTTL", function() {
let stub, req, res, next;
beforeEach(function () {
beforeEach(function() {
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
});
@@ -333,18 +332,18 @@ describe("Check Controller - updateCheckTTL", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
sinon.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);
expect(next.firstCall.args[0]).to.be.an("error");
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();
req.body = {
ttl: 1,
@@ -353,7 +352,7 @@ describe("Check Controller - updateCheckTTL", function () {
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 = {
ttl: 1,
};
@@ -362,7 +361,7 @@ describe("Check Controller - updateCheckTTL", function () {
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 = {
ttl: 1,
};
@@ -373,7 +372,7 @@ describe("Check Controller - updateCheckTTL", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.CHECK_UPDATE_TTL(req.language),
msg: successMessages.CHECK_UPDATE_TTL,
})
).to.be.true;
});

View File

@@ -11,12 +11,11 @@ import jwt from "jsonwebtoken";
import { successMessages } from "../../utils/messages.js";
import sinon from "sinon";
describe("maintenanceWindowController - createMaintenanceWindows", function () {
describe("maintenanceWindowController - createMaintenanceWindows", function() {
let req, res, next, stub;
beforeEach(function () {
beforeEach(function() {
req = {
language: 'en',
body: {
monitors: ["66ff52e7c5911c61698ac724"],
name: "window",
@@ -42,11 +41,11 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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(() => {
return { teamId: "123" };
});
@@ -57,14 +56,14 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
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());
await createMaintenanceWindows(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
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(() => {
return { teamId: "123" };
});
@@ -75,7 +74,7 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
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(() => {
return { teamId: "123" };
});
@@ -84,13 +83,13 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_CREATE(req.language),
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
})
).to.be.true;
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;
stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" };
@@ -100,17 +99,17 @@ describe("maintenanceWindowController - createMaintenanceWindows", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_CREATE(req.language),
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
})
).to.be.true;
stub.restore();
});
});
describe("maintenanceWindowController - getMaintenanceWindowById", function () {
describe("maintenanceWindowController - getMaintenanceWindowById", function() {
let req, res, next;
beforeEach(function () {
beforeEach(function() {
req = {
body: {},
params: {
@@ -122,7 +121,6 @@ describe("maintenanceWindowController - getMaintenanceWindowById", function () {
settingsService: {
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
},
language: 'en',
db: {
getMaintenanceWindowById: sinon.stub(),
},
@@ -134,38 +132,38 @@ describe("maintenanceWindowController - getMaintenanceWindowById", function () {
next = sinon.stub();
});
it("should reject if param validation fails", async function () {
it("should reject if param validation fails", async function() {
req.params = {};
await getMaintenanceWindowById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await getMaintenanceWindowById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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" });
await getMaintenanceWindowById(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID(req.language),
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
data: { id: "123" },
})
).to.be.true;
});
});
describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function () {
describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function() {
let req, res, next, stub;
beforeEach(function () {
beforeEach(function() {
req = {
body: {},
params: {},
@@ -179,7 +177,6 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
db: {
getMaintenanceWindowsByTeamId: sinon.stub(),
},
language: 'en',
};
res = {
status: sinon.stub().returnsThis(),
@@ -188,7 +185,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
next = sinon.stub();
});
it("should reject if query validation fails", async function () {
it("should reject if query validation fails", async function() {
req.query = {
invalid: 1,
};
@@ -197,14 +194,14 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
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());
await getMaintenanceWindowsByTeamId(req, res, next);
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
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(() => {
return { teamId: "123" };
});
@@ -215,7 +212,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
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(() => {
return { teamId: "123" };
});
@@ -225,7 +222,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM(req.language),
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
data: [{ id: jwt.verify().teamId }],
})
).to.be.true;
@@ -233,10 +230,10 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", function
});
});
describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", function () {
describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", function() {
let req, res, next;
beforeEach(function () {
beforeEach(function() {
req = {
body: {},
params: {
@@ -260,25 +257,25 @@ describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", funct
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
it("should reject if param validation fails", async function () {
it("should reject if param validation fails", async function() {
req.params = {};
await getMaintenanceWindowsByMonitorId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await getMaintenanceWindowsByMonitorId(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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" }];
req.db.getMaintenanceWindowsByMonitorId.returns(data);
await getMaintenanceWindowsByMonitorId(req, res, next);
@@ -287,17 +284,17 @@ describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", funct
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_MONITOR(req.language),
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_MONITOR,
data: data,
})
).to.be.true;
});
});
describe("maintenanceWindowController - deleteMaintenanceWindow", function () {
describe("maintenanceWindowController - deleteMaintenanceWindow", function() {
let req, res, next;
beforeEach(function () {
beforeEach(function() {
req = {
body: {},
params: {
@@ -321,47 +318,46 @@ describe("maintenanceWindowController - deleteMaintenanceWindow", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
it("should reject if param validation fails", async function () {
it("should reject if param validation fails", async function() {
req.params = {};
await deleteMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await deleteMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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);
expect(req.db.deleteMaintenanceWindowById.calledOnceWith(req.params.id));
expect(res.status.firstCall.args[0]).to.equal(200);
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_DELETE(req.language),
msg: successMessages.MAINTENANCE_WINDOW_DELETE,
})
).to.be.true;
});
});
describe("maintenanceWindowController - editMaintenanceWindow", function () {
describe("maintenanceWindowController - editMaintenanceWindow", function() {
let req, res, next;
beforeEach(function () {
beforeEach(function() {
req = {
body: {
active: true,
name: "test",
},
language: 'en',
params: {
id: "123",
},
@@ -383,32 +379,32 @@ describe("maintenanceWindowController - editMaintenanceWindow", function () {
next = sinon.stub();
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
it("should reject if param validation fails", async function () {
it("should reject if param validation fails", async function() {
req.params = {};
await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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 };
await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
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"));
await editMaintenanceWindow(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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" };
req.db.editMaintenanceWindowById.returns(data);
@@ -418,7 +414,7 @@ describe("maintenanceWindowController - editMaintenanceWindow", function () {
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.MAINTENANCE_WINDOW_EDIT(req.language),
msg: successMessages.MAINTENANCE_WINDOW_EDIT,
data: data,
})
).to.be.true;

File diff suppressed because it is too large Load Diff

View File

@@ -8,10 +8,10 @@ import {
import { successMessages } from "../../utils/messages.js";
import sinon from "sinon";
describe("Queue Controller - getMetrics", function () {
describe("Queue Controller - getMetrics", function() {
let req, res, next;
beforeEach(function () {
beforeEach(function() {
req = {
headers: {},
params: {},
@@ -32,14 +32,14 @@ describe("Queue Controller - getMetrics", function () {
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"));
await getMetrics(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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" };
req.jobQueue.getMetrics.returns(data);
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;
beforeEach(function () {
beforeEach(function() {
req = {
headers: {},
params: {},
@@ -76,14 +76,14 @@ describe("Queue Controller - getJobs", function () {
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"));
await getJobs(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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" };
req.jobQueue.getJobStats.returns(data);
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;
beforeEach(function () {
beforeEach(function() {
req = {
headers: {},
params: {},
@@ -120,14 +120,14 @@ describe("Queue Controller - addJob", function () {
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"));
await addJob(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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();
await addJob(req, res, next);
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;
beforeEach(function () {
beforeEach(function() {
req = {
headers: {},
params: {},
@@ -162,14 +162,14 @@ describe("Queue Controller - obliterateQueue", function () {
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"));
await obliterateQueue(req, res, next);
expect(next.firstCall.args[0]).to.be.an("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();
await obliterateQueue(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);

View File

@@ -7,33 +7,32 @@ import {
} from "../../db/mongo/modules/inviteModule.js";
import { errorMessages } from "../../utils/messages.js";
describe("Invite Module", function () {
describe("Invite Module", function() {
const mockUserData = {
email: "test@test.com",
teamId: "123",
role: ["admin"],
token: "123",
};
const mockLanguage = 'en';
const mockInviteToken = { _id: 123, time: 123 };
let inviteTokenDeleteManyStub,
inviteTokenSaveStub,
inviteTokenFindOneStub,
inviteTokenFindOneAndDeleteStub;
beforeEach(function () {
beforeEach(function() {
inviteTokenDeleteManyStub = sinon.stub(InviteToken, "deleteMany");
inviteTokenSaveStub = sinon.stub(InviteToken.prototype, "save");
inviteTokenFindOneStub = sinon.stub(InviteToken, "findOne");
inviteTokenFindOneAndDeleteStub = sinon.stub(InviteToken, "findOneAndDelete");
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
describe("requestInviteToken", function () {
it("should return a new invite token", async function () {
describe("requestInviteToken", function() {
it("should return a new invite token", async function() {
inviteTokenDeleteManyStub.resolves();
inviteTokenSaveStub.resolves();
const inviteToken = await requestInviteToken(mockUserData);
@@ -42,7 +41,7 @@ describe("Invite Module", function () {
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");
inviteTokenDeleteManyStub.rejects(err);
try {
@@ -53,23 +52,23 @@ describe("Invite Module", function () {
});
});
describe("getInviteToken", function () {
it("should return an invite token", async function () {
describe("getInviteToken", function() {
it("should return an invite token", async function() {
inviteTokenFindOneStub.resolves(mockInviteToken);
const inviteToken = await getInviteToken(mockUserData.token);
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);
try {
await getInviteToken(mockUserData.token);
} 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");
inviteTokenFindOneStub.rejects(err);
try {
@@ -81,23 +80,23 @@ describe("Invite Module", function () {
});
});
describe("getInviteTokenAndDelete", function () {
it("should return a deleted invite", async function () {
describe("getInviteTokenAndDelete", function() {
it("should return a deleted invite", async function() {
inviteTokenFindOneAndDeleteStub.resolves(mockInviteToken);
const deletedInvite = await getInviteTokenAndDelete(mockUserData.token);
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);
try {
await getInviteTokenAndDelete(mockUserData.token);
} 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");
inviteTokenFindOneAndDeleteStub.rejects(err);
try {

View File

@@ -31,7 +31,7 @@ import {
calculateGroupStats,
} from "../../db/mongo/modules/monitorModule.js";
describe("monitorModule", function () {
describe("monitorModule", function() {
let monitorFindStub,
monitorFindByIdStub,
monitorFindByIdAndUpdateStub,
@@ -43,7 +43,7 @@ describe("monitorModule", function () {
pageSpeedCheckFindStub,
hardwareCheckFindStub;
beforeEach(function () {
beforeEach(function() {
monitorFindStub = sinon.stub(Monitor, "find");
monitorFindByIdStub = sinon.stub(Monitor, "findById");
monitorFindByIdAndUpdateStub = sinon.stub(Monitor, "findByIdAndUpdate");
@@ -63,12 +63,12 @@ describe("monitorModule", function () {
});
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
describe("getAllMonitors", function () {
it("should return all monitors", async function () {
describe("getAllMonitors", function() {
it("should return all monitors", async function() {
const mockMonitors = [
{ _id: "1", name: "Monitor 1", url: "test1.com" },
{ _id: "2", name: "Monitor 2", url: "test2.com" },
@@ -81,13 +81,13 @@ describe("monitorModule", function () {
expect(monitorFindStub.firstCall.args).to.deep.equal([]);
});
it("should handle empty results", async function () {
it("should handle empty results", async function() {
monitorFindStub.returns([]);
const result = await getAllMonitors();
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
const error = new Error("Database error");
error.service = "MonitorModule";
@@ -105,8 +105,8 @@ describe("monitorModule", function () {
});
});
describe("getAllMonitorsWithUptimeStats", function () {
it("should return monitors with uptime stats for different time periods", async function () {
describe("getAllMonitorsWithUptimeStats", function() {
it("should return monitors with uptime stats for different time periods", async function() {
// Mock data
const mockMonitors = [
{
@@ -152,7 +152,7 @@ describe("monitorModule", function () {
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
const mockMonitors = [
{
@@ -198,7 +198,7 @@ describe("monitorModule", function () {
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
const mockMonitors = [
{
@@ -244,7 +244,7 @@ describe("monitorModule", function () {
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
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([]);
const result = await getAllMonitorsWithUptimeStats();
@@ -267,7 +267,7 @@ describe("monitorModule", function () {
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 = [
{
_id: "monitor1",
@@ -292,28 +292,28 @@ describe("monitorModule", function () {
});
});
describe("calculateUptimeDuration", function () {
describe("calculateUptimeDuration", function() {
let clock;
const NOW = new Date("2024-01-01T12:00:00Z").getTime();
beforeEach(function () {
beforeEach(function() {
// Fix the current time
clock = sinon.useFakeTimers(NOW);
});
afterEach(function () {
afterEach(function() {
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);
});
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);
});
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 = [
{ status: true, createdAt: "2024-01-01T11:00:00Z" }, // Most recent
{ status: true, createdAt: "2024-01-01T10:00:00Z" },
@@ -325,7 +325,7 @@ describe("monitorModule", function () {
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 = [
{ status: true, createdAt: "2024-01-01T11: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;
const NOW = new Date("2024-01-01T12:00:00Z").getTime();
beforeEach(function () {
beforeEach(function() {
// Fix the current time
clock = sinon.useFakeTimers(NOW);
});
afterEach(function () {
afterEach(function() {
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);
});
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);
});
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 = [
{ createdAt: "2024-01-01T11:30:00Z" }, // 30 minutes ago
{ createdAt: "2024-01-01T11:00:00Z" },
@@ -369,7 +369,7 @@ describe("monitorModule", function () {
expect(getLastChecked(checks)).to.equal(1800000);
});
it("should handle checks from different days", function () {
it("should handle checks from different days", function() {
const checks = [
{ createdAt: "2023-12-31T12:00:00Z" }, // 24 hours ago
{ createdAt: "2023-12-30T12:00:00Z" },
@@ -380,16 +380,16 @@ describe("monitorModule", function () {
});
});
describe("getLatestResponseTime", function () {
it("should return 0 when checks array is empty", function () {
describe("getLatestResponseTime", function() {
it("should return 0 when checks array is empty", function() {
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);
});
it("should return response time from most recent check", function () {
it("should return response time from most recent check", function() {
const checks = [
{ responseTime: 150, createdAt: "2024-01-01T11:30:00Z" }, // Most recent
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -399,7 +399,7 @@ describe("monitorModule", function () {
expect(getLatestResponseTime(checks)).to.equal(150);
});
it("should handle missing responseTime in checks", function () {
it("should handle missing responseTime in checks", function() {
const checks = [
{ createdAt: "2024-01-01T11:30:00Z" },
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -409,16 +409,16 @@ describe("monitorModule", function () {
});
});
describe("getAverageResponseTime", function () {
it("should return 0 when checks array is empty", function () {
describe("getAverageResponseTime", function() {
it("should return 0 when checks array is empty", function() {
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);
});
it("should calculate average response time from all checks", function () {
it("should calculate average response time from all checks", function() {
const checks = [
{ responseTime: 100, createdAt: "2024-01-01T11:30:00Z" },
{ responseTime: 200, createdAt: "2024-01-01T11:00:00Z" },
@@ -429,7 +429,7 @@ describe("monitorModule", function () {
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 = [
{ responseTime: 100, createdAt: "2024-01-01T11:30:00Z" },
{ createdAt: "2024-01-01T11:00:00Z" },
@@ -440,7 +440,7 @@ describe("monitorModule", function () {
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 = [
{ createdAt: "2024-01-01T11:30:00Z" },
{ createdAt: "2024-01-01T11:00:00Z" },
@@ -450,26 +450,26 @@ describe("monitorModule", function () {
});
});
describe("getUptimePercentage", function () {
it("should return 0 when checks array is empty", function () {
describe("getUptimePercentage", function() {
it("should return 0 when checks array is empty", function() {
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);
});
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 }];
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 }];
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 = [
{ status: true },
{ status: false },
@@ -480,33 +480,33 @@ describe("monitorModule", function () {
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 }];
// 2 up out of 3 total ≈ 66.67%
expect(getUptimePercentage(checks)).to.equal((2 / 3) * 100);
});
});
describe("getIncidents", function () {
it("should return 0 when checks array is empty", function () {
describe("getIncidents", function() {
it("should return 0 when checks array is empty", function() {
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);
});
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 }];
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 }];
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 = [
{ status: true },
{ status: false },
@@ -517,7 +517,7 @@ describe("monitorModule", function () {
expect(getIncidents(checks)).to.equal(2);
});
it("should handle undefined status values", function () {
it("should handle undefined status values", function() {
const checks = [
{ status: true },
{ status: undefined },
@@ -529,10 +529,10 @@ describe("monitorModule", function () {
});
});
describe("getMonitorChecks", function () {
describe("getMonitorChecks", function() {
let mockModel;
beforeEach(function () {
beforeEach(function() {
// Create a mock model with chainable methods
const mockChecks = [
{ monitorId: "123", createdAt: new Date("2024-01-01") },
@@ -546,11 +546,11 @@ describe("monitorModule", function () {
};
});
afterEach(function () {
afterEach(function() {
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
const monitorId = "123";
const dateRange = {
@@ -579,7 +579,7 @@ describe("monitorModule", function () {
});
});
it("should handle empty results", async function () {
it("should handle empty results", async function() {
// Arrange
const emptyModel = {
find: sinon.stub().returns({
@@ -603,7 +603,7 @@ describe("monitorModule", function () {
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
const sortedChecks = [
{ monitorId: "123", createdAt: new Date("2024-01-02") },
@@ -637,39 +637,39 @@ describe("monitorModule", function () {
});
});
describe("processChecksForDisplay", function () {
describe("processChecksForDisplay", function() {
let normalizeStub;
beforeEach(function () {
beforeEach(function() {
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 result = processChecksForDisplay(normalizeStub, 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 result = processChecksForDisplay(normalizeStub, checks, 5);
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 result = processChecksForDisplay(normalizeStub, checks, 3);
// Should return [1, 3, 5] as n = ceil(6/3) = 2
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 result = processChecksForDisplay(normalizeStub, checks, 3);
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];
normalizeStub.returns([10, 20, 30]);
@@ -679,7 +679,7 @@ describe("monitorModule", function () {
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];
normalizeStub.returns([10, 30, 50]);
@@ -690,7 +690,7 @@ describe("monitorModule", function () {
});
});
describe("groupChecksByTime", function () {
describe("groupChecksByTime", function() {
const mockChecks = [
{ createdAt: "2024-01-15T10:30:45Z" },
{ createdAt: "2024-01-15T10:45:15Z" },
@@ -698,7 +698,7 @@ describe("monitorModule", function () {
{ 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");
// 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);
});
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");
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);
});
it("should handle empty checks array", function () {
it("should handle empty checks array", function() {
const result = groupChecksByTime([], "day");
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 result = groupChecksByTime(singleCheck, "day");
@@ -735,7 +735,7 @@ describe("monitorModule", function () {
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 = [
{ createdAt: "invalid-date" },
{ 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");
});
it("should handle checks in same time group", function () {
it("should handle checks in same time group", function() {
const checksInSameHour = [
{ createdAt: "2024-01-15T10:15:00Z" },
{ createdAt: "2024-01-15T10:45:00Z" },
@@ -766,16 +766,16 @@ describe("monitorModule", function () {
});
});
describe("calculateGroupStats", function () {
describe("calculateGroupStats", function() {
// Mock getUptimePercentage function
let uptimePercentageStub;
beforeEach(function () {
beforeEach(function() {
uptimePercentageStub = sinon.stub();
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 = {
time: "2024-01-15",
checks: [
@@ -796,7 +796,7 @@ describe("monitorModule", function () {
});
});
it("should handle empty checks array", function () {
it("should handle empty checks array", function() {
const mockGroup = {
time: "2024-01-15",
checks: [],
@@ -813,7 +813,7 @@ describe("monitorModule", function () {
});
});
it("should handle missing responseTime values", function () {
it("should handle missing responseTime values", function() {
const mockGroup = {
time: "2024-01-15",
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 = {
time: "2024-01-15",
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 = {
time: "2024-01-15",
checks: [
@@ -877,7 +877,7 @@ describe("monitorModule", function () {
});
});
describe("getMonitorStatsById", function () {
describe("getMonitorStatsById", function() {
const now = new Date();
const oneHourAgo = new Date(now - 3600000);
const twoHoursAgo = new Date(now - 7200000);
@@ -974,18 +974,18 @@ describe("monitorModule", function () {
},
};
beforeEach(function () {
beforeEach(function() {
checkFindStub.returns({
sort: () => checkDocs,
});
monitorFindByIdStub.returns(mockMonitor);
});
afterEach(function () {
afterEach(function() {
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";
const result = await getMonitorStatsById(req);
expect(result).to.include.keys([
@@ -1009,7 +1009,7 @@ describe("monitorModule", function () {
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);
req.query.sortOrder = "desc";
const result = await getMonitorStatsById(req);
@@ -1034,7 +1034,7 @@ describe("monitorModule", function () {
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);
req.query.sortOrder = "desc";
const result = await getMonitorStatsById(req);
@@ -1059,7 +1059,7 @@ describe("monitorModule", function () {
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";
const result = await getMonitorStatsById(req);
expect(result).to.include.keys([
@@ -1083,7 +1083,7 @@ describe("monitorModule", function () {
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));
const req = {
@@ -1101,21 +1101,21 @@ describe("monitorModule", function () {
});
});
describe("getMonitorById", function () {
describe("getMonitorById", function() {
let notificationFindStub;
let monitorSaveStub;
beforeEach(function () {
beforeEach(function() {
// Create stubs
notificationFindStub = sinon.stub(Notification, "find");
monitorSaveStub = sinon.stub().resolves();
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
it("should return monitor with notifications when found", async function () {
it("should return monitor with notifications when found", async function() {
// Arrange
const monitorId = "123";
const mockMonitor = {
@@ -1139,10 +1139,9 @@ describe("monitorModule", function () {
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
const monitorId = "nonexistent";
const mockLanguage = 'en';
monitorFindByIdStub.resolves(null);
// Act & Assert
@@ -1150,14 +1149,14 @@ describe("monitorModule", function () {
await getMonitorById(monitorId);
expect.fail("Should have thrown an 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.service).to.equal("monitorModule");
expect(error.method).to.equal("getMonitorById");
}
});
it("should handle database errors properly", async function () {
it("should handle database errors properly", async function() {
// Arrange
const monitorId = "123";
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
const monitorId = "123";
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
const monitorId = "123";
const mockMonitor = {
@@ -1223,8 +1222,8 @@ describe("monitorModule", function () {
});
});
describe("getMonitorsAndSummaryByTeamId", function () {
it("should return monitors and correct summary counts", async function () {
describe("getMonitorsAndSummaryByTeamId", function() {
it("should return monitors and correct summary counts", async function() {
// Arrange
const teamId = "team123";
const type = "http";
@@ -1250,7 +1249,7 @@ describe("monitorModule", function () {
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
monitorFindStub.resolves([]);
@@ -1267,7 +1266,7 @@ describe("monitorModule", function () {
});
});
it("should handle database errors", async function () {
it("should handle database errors", async function() {
// Arrange
const error = new Error("Database error");
error.service = "MonitorModule";
@@ -1286,8 +1285,8 @@ describe("monitorModule", function () {
});
});
describe("getMonitorsByTeamId", function () {
beforeEach(function () {
describe("getMonitorsByTeamId", function() {
beforeEach(function() {
// Chain stubs for Monitor.find().skip().limit().sort()
// Stub for CHECK_MODEL_LOOKUP model find
@@ -1298,11 +1297,11 @@ describe("monitorModule", function () {
});
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
it("should return monitors with basic query parameters", async function () {
it("should return monitors with basic query parameters", async function() {
const mockMonitors = [
{ _id: "1", type: "http", toObject: () => ({ _id: "1", type: "http" }) },
{ _id: "2", type: "ping", toObject: () => ({ _id: "2", type: "ping" }) },
@@ -1335,7 +1334,7 @@ describe("monitorModule", function () {
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 = [
{ _id: "1", type: "http", toObject: () => ({ _id: "1", type: "http" }) },
{ _id: "2", type: "ping", toObject: () => ({ _id: "2", type: "ping" }) },
@@ -1368,7 +1367,7 @@ describe("monitorModule", function () {
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 = {
params: { teamId: "team123" },
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 = {
params: { teamId: "team123" },
query: {
@@ -1421,7 +1420,7 @@ describe("monitorModule", function () {
});
});
it("should handle pagination parameters", async function () {
it("should handle pagination parameters", async function() {
const req = {
params: { teamId: "team123" },
query: {
@@ -1446,7 +1445,7 @@ describe("monitorModule", function () {
});
});
it("should handle sorting parameters", async function () {
it("should handle sorting parameters", async function() {
const req = {
params: { teamId: "team123" },
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
const req = {
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 = {
params: { teamId: "team123" },
query: { normalize: "true" },
@@ -1532,7 +1531,7 @@ describe("monitorModule", function () {
expect(result.monitors).to.have.lengthOf(2);
});
it("should handle database errors", async function () {
it("should handle database errors", async function() {
const req = {
params: { teamId: "team123" },
query: {},
@@ -1558,8 +1557,8 @@ describe("monitorModule", function () {
});
});
describe("createMonitor", function () {
it("should create a monitor without notifications", async function () {
describe("createMonitor", function() {
it("should create a monitor without notifications", async function() {
let monitorSaveStub = sinon.stub(Monitor.prototype, "save").resolves();
const req = {
@@ -1584,7 +1583,7 @@ describe("monitorModule", function () {
expect(result.url).to.equal(expectedMonitor.url);
});
it("should handle database errors", async function () {
it("should handle database errors", async function() {
const req = {
body: {
name: "Test Monitor",
@@ -1601,8 +1600,8 @@ describe("monitorModule", function () {
});
});
describe("deleteMonitor", function () {
it("should delete a monitor successfully", async function () {
describe("deleteMonitor", function() {
it("should delete a monitor successfully", async function() {
const monitorId = "123456789";
const mockMonitor = {
_id: monitorId,
@@ -1622,11 +1621,10 @@ describe("monitorModule", function () {
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 req = {
params: { monitorId },
language: 'en',
};
monitorFindByIdAndDeleteStub.resolves(null);
@@ -1635,13 +1633,13 @@ describe("monitorModule", function () {
await deleteMonitor(req);
expect.fail("Should have thrown an error");
} 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.method).to.equal("deleteMonitor");
}
});
it("should handle database errors", async function () {
it("should handle database errors", async function() {
const monitorId = "123456789";
const req = {
params: { monitorId },
@@ -1661,8 +1659,8 @@ describe("monitorModule", function () {
});
});
describe("deleteAllMonitors", function () {
it("should delete all monitors for a team successfully", async function () {
describe("deleteAllMonitors", function() {
it("should delete all monitors for a team successfully", async function() {
const teamId = "team123";
const mockMonitors = [
{ _id: "1", name: "Monitor 1", teamId },
@@ -1682,7 +1680,7 @@ describe("monitorModule", function () {
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";
monitorFindStub.resolves([]);
@@ -1698,7 +1696,7 @@ describe("monitorModule", function () {
sinon.assert.calledWith(monitorDeleteManyStub, { teamId });
});
it("should handle database errors", async function () {
it("should handle database errors", async function() {
const teamId = "team123";
const dbError = new Error("Database connection error");
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";
monitorFindStub.resolves([{ _id: "1", name: "Monitor 1" }]);
monitorDeleteManyStub.rejects(new Error("Delete operation failed"));
@@ -1727,14 +1725,14 @@ describe("monitorModule", function () {
});
});
describe("deleteMonitorsByUserId", function () {
beforeEach(function () { });
describe("deleteMonitorsByUserId", function() {
beforeEach(function() {});
afterEach(function () {
afterEach(function() {
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
const userId = "user123";
const mockResult = {
@@ -1752,7 +1750,7 @@ describe("monitorModule", function () {
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
const userId = "nonexistentUser";
const mockResult = {
@@ -1770,7 +1768,7 @@ describe("monitorModule", function () {
sinon.assert.calledWith(monitorDeleteManyStub, { userId: userId });
});
it("should handle database errors", async function () {
it("should handle database errors", async function() {
// Arrange
const userId = "user123";
const dbError = new Error("Database connection error");
@@ -1788,8 +1786,8 @@ describe("monitorModule", function () {
});
});
describe("editMonitor", function () {
it("should edit a monitor successfully", async function () {
describe("editMonitor", function() {
it("should edit a monitor successfully", async function() {
// Arrange
const candidateId = "monitor123";
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
const candidateId = "nonexistent123";
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
const candidateId = "monitor123";
const candidateMonitor = {
@@ -1882,7 +1880,7 @@ describe("monitorModule", function () {
);
});
it("should handle database errors", async function () {
it("should handle database errors", async function() {
// Arrange
const candidateId = "monitor123";
const candidateMonitor = {
@@ -1904,8 +1902,8 @@ describe("monitorModule", function () {
});
});
describe("addDemoMonitors", function () {
it("should add demo monitors successfully", async function () {
describe("addDemoMonitors", function() {
it("should add demo monitors successfully", async function() {
// Arrange
const userId = "user123";
const teamId = "team123";
@@ -1914,7 +1912,7 @@ describe("monitorModule", function () {
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 teamId = "team123";

View File

@@ -43,7 +43,7 @@ const createQueryChain = (finalResult, comparePasswordResult = false) => ({
save: sinon.stub().resolves(),
});
describe("recoveryModule", function () {
describe("recoveryModule", function() {
let deleteManyStub,
saveStub,
findOneStub,
@@ -52,10 +52,9 @@ describe("recoveryModule", function () {
userFindOneStub;
let req, res;
beforeEach(function () {
beforeEach(function() {
req = {
body: { email: "test@test.com" },
language: 'en',
};
deleteManyStub = sinon.stub(RecoveryToken, "deleteMany");
saveStub = sinon.stub(RecoveryToken.prototype, "save");
@@ -65,19 +64,19 @@ describe("recoveryModule", function () {
userFindOneStub = sinon.stub().resolves();
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
describe("requestRecoveryToken", function () {
it("should return a recovery token", async function () {
describe("requestRecoveryToken", function() {
it("should return a recovery token", async function() {
deleteManyStub.resolves();
saveStub.resolves(mockRecoveryToken);
const result = await requestRecoveryToken(req, res);
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");
deleteManyStub.rejects(err);
try {
@@ -89,24 +88,24 @@ describe("recoveryModule", function () {
});
});
describe("validateRecoveryToken", function () {
it("should return a recovery token if found", async function () {
describe("validateRecoveryToken", function() {
it("should return a recovery token if found", async function() {
findOneStub.resolves(mockRecoveryToken);
const result = await validateRecoveryToken(req, res);
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);
try {
await validateRecoveryToken(req, res);
} catch (error) {
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");
findOneStub.rejects(err);
try {
@@ -118,41 +117,40 @@ describe("recoveryModule", function () {
});
});
describe("resetPassword", function () {
beforeEach(function () {
describe("resetPassword", function() {
beforeEach(function() {
req.body = {
password: "test",
newPassword: "test1",
};
req.language = 'en';
});
afterEach(function () {
afterEach(function() {
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);
try {
await resetPassword(req, res);
} catch (error) {
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);
userFindOneStub = sinon.stub(User, "findOne").resolves(null);
try {
await resetPassword(req, res);
} catch (error) {
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);
saveStub.resolves();
userFindOneStub = sinon
@@ -162,11 +160,11 @@ describe("recoveryModule", function () {
await resetPassword(req, res);
} catch (error) {
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);
saveStub.resolves();
userFindOneStub = sinon

View File

@@ -6,32 +6,31 @@ import {
import StatusPage from "../../db/models/StatusPage.js";
import { errorMessages } from "../../utils/messages.js";
describe("statusPageModule", function () {
let statusPageFindOneStub, statusPageSaveStub, statusPageFindStub, mockLanguage;
describe("statusPageModule", function() {
let statusPageFindOneStub, statusPageSaveStub, statusPageFindStub;
beforeEach(function () {
mockLanguage = 'en';
beforeEach(function() {
statusPageSaveStub = sinon.stub(StatusPage.prototype, "save");
statusPageFindOneStub = sinon.stub(StatusPage, "findOne");
statusPageFindStub = sinon.stub(StatusPage, "find");
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
describe("createStatusPage", function () {
it("should throw an error if a non-unique url is provided", async function () {
describe("createStatusPage", function() {
it("should throw an error if a non-unique url is provided", async function() {
statusPageFindOneStub.resolves(true);
try {
await createStatusPage({ url: "test" });
} catch (error) {
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");
err.code = 11000;
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);
statusPageFindStub.resolves([]);
const mockStatusPage = { url: "test" };
@@ -52,21 +51,21 @@ describe("statusPageModule", function () {
});
});
describe("getStatusPageByUrl", function () {
it("should throw an error if a status page is not found", async function () {
describe("getStatusPageByUrl", function() {
it("should throw an error if a status page is not found", async function() {
statusPageFindOneStub.resolves(null);
try {
await getStatusPageByUrl("test");
} catch (error) {
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" };
statusPageFindOneStub.resolves(mockStatusPage);
const statusPage = await getStatusPageByUrl(mockStatusPage.url, mockLanguage);
const statusPage = await getStatusPageByUrl(mockStatusPage.url);
expect(statusPage).to.exist;
expect(statusPage).to.deep.equal(mockStatusPage);
});

View File

@@ -27,9 +27,7 @@ const imageFile = {
image: 1,
};
const mockLanguage = 'en';
describe("userModule", function () {
describe("userModule", function() {
let teamSaveStub,
teamFindByIdAndDeleteStub,
userSaveStub,
@@ -42,7 +40,7 @@ describe("userModule", function () {
generateAvatarImageStub,
parseBooleanStub;
beforeEach(function () {
beforeEach(function() {
teamSaveStub = sinon.stub(TeamModel.prototype, "save");
teamFindByIdAndDeleteStub = sinon.stub(TeamModel, "findByIdAndDelete");
userSaveStub = sinon.stub(UserModel.prototype, "save");
@@ -56,12 +54,12 @@ describe("userModule", function () {
parseBooleanStub = sinon.stub().returns(true);
});
afterEach(function () {
afterEach(function() {
sinon.restore();
});
describe("insertUser", function () {
it("should insert a regular user", async function () {
describe("insertUser", function() {
it("should insert a regular user", async function() {
userSaveStub.resolves(mockUser);
userFindOneStub.returns({
select: sinon.stub().returns({
@@ -72,7 +70,7 @@ describe("userModule", function () {
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);
userFindOneStub.returns({
select: sinon.stub().returns({
@@ -83,7 +81,7 @@ describe("userModule", function () {
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");
userSaveStub.rejects(err);
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");
err.code = 11000;
userSaveStub.rejects(err);
@@ -107,8 +105,8 @@ describe("userModule", function () {
});
});
describe("getUserByEmail", function () {
it("should return a user", async function () {
describe("getUserByEmail", function() {
it("should return a user", async function() {
userFindOneStub.returns({
select: sinon.stub().resolves(mockUser),
});
@@ -117,23 +115,23 @@ describe("userModule", function () {
});
});
describe("getUserByEmail", function () {
it("throw an error if a user is not found", async function () {
describe("getUserByEmail", function() {
it("throw an error if a user is not found", async function() {
userFindOneStub.returns({
select: sinon.stub().resolves(null),
});
try {
await getUserByEmail(mockUser.email);
} 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;
beforeEach(function () {
beforeEach(function() {
req = {
params: {
userId: "testId",
@@ -150,9 +148,9 @@ describe("userModule", function () {
res = {};
});
afterEach(function () { });
afterEach(function() {});
it("should update a user", async function () {
it("should update a user", async function() {
parseBooleanStub.returns(false);
userFindByIdAndUpdateStub.returns({
select: sinon.stub().returns({
@@ -168,7 +166,7 @@ describe("userModule", function () {
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";
userFindByIdAndUpdateStub.returns({
select: sinon.stub().returns({
@@ -184,7 +182,7 @@ describe("userModule", function () {
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");
userFindByIdAndUpdateStub.throws(err);
try {
@@ -196,23 +194,23 @@ describe("userModule", function () {
});
});
describe("deleteUser", function () {
it("should return a deleted user", async function () {
describe("deleteUser", function() {
it("should return a deleted user", async function() {
userFindByIdAndDeleteStub.resolves(mockUser);
const result = await deleteUser("testId");
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 {
await deleteUser("testId");
} catch (error) {
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");
userFindByIdAndDeleteStub.throws(err);
try {
@@ -224,14 +222,14 @@ describe("userModule", function () {
});
});
describe("deleteTeam", function () {
it("should return true if team deleted", async function () {
describe("deleteTeam", function() {
it("should return true if team deleted", async function() {
teamFindByIdAndDeleteStub.resolves();
const result = await deleteTeam("testId");
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");
teamFindByIdAndDeleteStub.throws(err);
try {
@@ -243,14 +241,14 @@ describe("userModule", function () {
});
});
describe("deleteAllOtherUsers", function () {
it("should return true if all other users deleted", async function () {
describe("deleteAllOtherUsers", function() {
it("should return true if all other users deleted", async function() {
userDeleteManyStub.resolves(true);
const result = await deleteAllOtherUsers();
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");
userDeleteManyStub.throws(err);
try {
@@ -262,8 +260,8 @@ describe("userModule", function () {
});
});
describe("getAllUsers", function () {
it("should return all users", async function () {
describe("getAllUsers", function() {
it("should return all users", async function() {
userFindStub.returns({
select: sinon.stub().returns({
select: sinon.stub().resolves([mockUser]),
@@ -273,7 +271,7 @@ describe("userModule", function () {
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");
userFindStub.throws(err);
try {
@@ -285,14 +283,14 @@ describe("userModule", function () {
});
});
describe("logoutUser", function () {
it("should return true if user logged out", async function () {
describe("logoutUser", function() {
it("should return true if user logged out", async function() {
userUpdateOneStub.resolves(true);
const result = await logoutUser("testId");
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");
userUpdateOneStub.throws(err);
try {

View File

@@ -3,10 +3,10 @@ import NetworkService from "../../service/networkService.js";
import { expect } from "chai";
import http from "http";
import { errorMessages } from "../../utils/messages.js";
describe("Network Service", function () {
describe("Network Service", function() {
let axios, ping, Docker, logger, networkService;
beforeEach(function () {
beforeEach(function() {
axios = {
get: sinon.stub().resolves({
data: { foo: "bar" },
@@ -35,22 +35,22 @@ describe("Network Service", function () {
networkService = new NetworkService(axios, ping, logger, http, Docker);
});
describe("constructor", function () {
it("should create a new NetworkService instance", function () {
describe("constructor", function() {
it("should create a new NetworkService instance", function() {
const networkService = new NetworkService();
expect(networkService).to.be.an.instanceOf(NetworkService);
});
});
describe("timeRequest", function () {
it("should time an asynchronous operation", async function () {
describe("timeRequest", function() {
it("should time an asynchronous operation", async function() {
const operation = sinon.stub().resolves("success");
const { response, responseTime } = await networkService.timeRequest(operation);
expect(response).to.equal("success");
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 operation = sinon.stub().throws(error);
const { response, responseTime } = await networkService.timeRequest(operation);
@@ -60,8 +60,8 @@ describe("Network Service", function () {
});
});
describe("requestPing", function () {
it("should return a response object if ping successful", async function () {
describe("requestPing", function() {
it("should return a response object if ping successful", async function() {
const pingResult = await networkService.requestPing({
data: { url: "http://test.com", _id: "123" },
});
@@ -71,7 +71,7 @@ describe("Network Service", function () {
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");
networkService.timeRequest = sinon
.stub()
@@ -86,7 +86,7 @@ describe("Network Service", function () {
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");
networkService.timeRequest = sinon.stub().throws(error);
try {
@@ -100,8 +100,8 @@ describe("Network Service", function () {
});
});
describe("requestHttp", function () {
it("should return a response object if http successful", async function () {
describe("requestHttp", function() {
it("should return a response object if http successful", async function() {
const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
const httpResult = await networkService.requestHttp(job);
expect(httpResult.monitorId).to.equal("123");
@@ -110,7 +110,7 @@ describe("Network Service", function () {
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");
error.response = { status: 404 };
networkService.timeRequest = sinon
@@ -125,7 +125,7 @@ describe("Network Service", function () {
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");
error.response = {};
networkService.timeRequest = sinon
@@ -140,7 +140,7 @@ describe("Network Service", function () {
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");
networkService.timeRequest = sinon.stub().throws(error);
try {
@@ -154,8 +154,8 @@ describe("Network Service", function () {
});
});
describe("requestPagespeed", function () {
it("should return a response object if pagespeed successful", async function () {
describe("requestPagespeed", function() {
it("should return a response object if pagespeed successful", async function() {
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
const pagespeedResult = await networkService.requestPagespeed(job);
expect(pagespeedResult.monitorId).to.equal("123");
@@ -164,7 +164,7 @@ describe("Network Service", function () {
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");
error.response = { status: 404 };
networkService.timeRequest = sinon
@@ -179,7 +179,7 @@ describe("Network Service", function () {
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");
error.response = {};
networkService.timeRequest = sinon
@@ -194,7 +194,7 @@ describe("Network Service", function () {
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");
networkService.timeRequest = sinon.stub().throws(error);
try {
@@ -208,8 +208,8 @@ describe("Network Service", function () {
});
});
describe("requestHardware", function () {
it("should return a response object if hardware successful", async function () {
describe("requestHardware", function() {
it("should return a response object if hardware successful", async function() {
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
const httpResult = await networkService.requestHardware(job);
expect(httpResult.monitorId).to.equal("123");
@@ -218,7 +218,7 @@ describe("Network Service", function () {
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 = {
data: {
url: "http://test.com",
@@ -234,7 +234,7 @@ describe("Network Service", function () {
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");
error.response = { status: 404 };
networkService.timeRequest = sinon
@@ -249,7 +249,7 @@ describe("Network Service", function () {
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");
error.response = {};
networkService.timeRequest = sinon
@@ -264,7 +264,7 @@ describe("Network Service", function () {
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");
networkService.timeRequest = sinon.stub().throws(error);
try {
@@ -278,8 +278,8 @@ describe("Network Service", function () {
});
});
describe("requestDocker", function () {
it("should return a response object if docker successful", async function () {
describe("requestDocker", function() {
it("should return a response object if docker successful", async function() {
const job = { data: { url: "http://test.com", _id: "123", type: "docker" } };
const dockerResult = await networkService.requestDocker(job);
expect(dockerResult.monitorId).to.equal("123");
@@ -288,7 +288,7 @@ describe("Network Service", function () {
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 {
listContainers = sinon.stub().resolves([
{
@@ -307,7 +307,7 @@ describe("Network Service", function () {
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 {
listContainers = sinon.stub().resolves([
{
@@ -326,7 +326,7 @@ describe("Network Service", function () {
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 {
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 {
listContainers = sinon.stub().resolves([]);
getContainer = sinon.stub().throws(new Error("test error"));
@@ -355,13 +355,13 @@ describe("Network Service", function () {
try {
await networkService.requestDocker(job);
} catch (error) {
expect(error.message).to.equal(errorMessages.DOCKER_NOT_FOUND(mockLanguage));
expect(error.message).to.equal(errorMessages.DOCKER_NOT_FOUND);
}
});
});
describe("getStatus", function () {
beforeEach(function () {
describe("getStatus", function() {
beforeEach(function() {
networkService.requestPing = sinon.stub();
networkService.requestHttp = sinon.stub();
networkService.requestPagespeed = sinon.stub();
@@ -369,11 +369,11 @@ describe("Network Service", function () {
networkService.requestDocker = sinon.stub();
});
afterEach(function () {
afterEach(function() {
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" } });
expect(networkService.requestPing.calledOnce).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;
});
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" } });
expect(networkService.requestPing.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;
});
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" } });
expect(networkService.requestPing.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;
});
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" } });
expect(networkService.requestHardware.calledOnce).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;
});
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" } });
expect(networkService.requestDocker.calledOnce).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;
});
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 {
await networkService.getStatus({ data: { type: "unknown" } });
} 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 {
await networkService.getStatus({ data: { type: undefined } });
} 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 {
await networkService.getStatus({});
} 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 {
await networkService.getStatus(null);
} catch (error) {

View File

@@ -1,25 +1,23 @@
import { errorMessages, successMessages } from "../../utils/messages.js";
describe("Messages", function () {
describe("messages - errorMessages", function () {
it("should have a DB_FIND_MONITOR_BY_ID function", function () {
describe("Messages", function() {
describe("messages - errorMessages", function() {
it("should have a DB_FIND_MONITOR_BY_ID function", function() {
const monitorId = "12345";
const mockLanguage = 'en';
expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId, mockLanguage)).to.equal(
expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)).to.equal(
`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 mockLanguage = 'en';
expect(errorMessages.DB_DELETE_CHECKS(monitorId, mockLanguage)).to.equal(
expect(errorMessages.DB_DELETE_CHECKS(monitorId)).to.equal(
`No checks found for monitor with id ${monitorId}`
);
});
});
describe("messages - successMessages", function () {
it("should have a MONITOR_GET_BY_USER_ID function", function () {
describe("messages - successMessages", function() {
it("should have a MONITOR_GET_BY_USER_ID function", function() {
const userId = "12345";
expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal(
`Got monitor for ${userId} successfully"`