Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/be/tests-recovery-module #1145

Merged
merged 1 commit into from
Nov 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions Server/tests/db/recoveryModule.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import sinon from "sinon";
import RecoveryToken from "../../db/models/RecoveryToken.js";
import User from "../../db/models/User.js";
import {
requestRecoveryToken,
validateRecoveryToken,
resetPassword,
} from "../../db/mongo/modules/recoveryModule.js";
import { errorMessages } from "../../utils/messages.js";

const mockRecoveryToken = {
email: "[email protected]",
token: "1234567890",
};

const mockUser = {
email: "[email protected]",
password: "oldPassword",
};

const mockUserWithoutPassword = {
email: "[email protected]",
};

// Create a query builder that logs
const createQueryChain = (finalResult, comparePasswordResult = false) => ({
select: () => ({
select: async () => {
if (finalResult === mockUser) {
// Return a new object with all required methods
return {
email: "[email protected]",
password: "oldPassword",
comparePassword: sinon.stub().resolves(comparePasswordResult),
save: sinon.stub().resolves(),
};
}
return finalResult;
},
}),
// Add methods to the top level too
comparePassword: sinon.stub().resolves(comparePasswordResult),
save: sinon.stub().resolves(),
});

describe("recoveryModule", () => {
let deleteManyStub,
saveStub,
findOneStub,
userCompareStub,
userSaveStub,
userFindOneStub;
let req, res;
beforeEach(() => {
req = {
body: { email: "[email protected]" },
};
deleteManyStub = sinon.stub(RecoveryToken, "deleteMany");
saveStub = sinon.stub(RecoveryToken.prototype, "save");
findOneStub = sinon.stub(RecoveryToken, "findOne");
userCompareStub = sinon.stub(User.prototype, "comparePassword");
userSaveStub = sinon.stub(User.prototype, "save");
userFindOneStub = sinon.stub().resolves();
});

afterEach(() => {
sinon.restore();
});

describe("requestRecoveryToken", () => {
it("should return a recovery token", async () => {
deleteManyStub.resolves();
saveStub.resolves(mockRecoveryToken);
const result = await requestRecoveryToken(req, res);
expect(result.email).to.equal(mockRecoveryToken.email);
});
it("should handle an error", async () => {
const err = new Error("Test error");
deleteManyStub.rejects(err);
try {
await requestRecoveryToken(req, res);
} catch (error) {
expect(error).to.exist;
expect(error).to.deep.equal(err);
}
});
});
Comment on lines +70 to +87
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Knees weak, test coverage's heavy! We're missing some cases! 🤔

The test suite for requestRecoveryToken is missing some important scenarios:

Add these test cases:

  1. Invalid email format
  2. Empty email
  3. Case where save fails but delete succeeds
  4. Verify the token format/structure

Here's a sample test case:

it("should validate email format", async () => {
  req.body.email = "invalid-email";
  try {
    await requestRecoveryToken(req, res);
  } catch (error) {
    expect(error.message).to.equal(errorMessages.INVALID_EMAIL_FORMAT);
  }
});

describe("validateRecoveryToken", () => {
it("should return a recovery token if found", async () => {
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 () => {
findOneStub.resolves(null);
try {
await validateRecoveryToken(req, res);
} catch (error) {
expect(error).to.exist;
expect(error.message).to.equal(errorMessages.DB_TOKEN_NOT_FOUND);
}
});
it("should handle DB errors", async () => {
const err = new Error("Test error");
findOneStub.rejects(err);
try {
await validateRecoveryToken(req, res);
} catch (error) {
expect(error).to.exist;
expect(error).to.deep.equal(err);
}
});
});
Comment on lines +88 to +113
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

There's vomit on his sweater already - we forgot to test token expiration! 😰

The validateRecoveryToken tests should include token expiration scenarios.

Add a test case for expired tokens:

it("should throw an error if token is expired", async () => {
  const expiredToken = {
    ...mockRecoveryToken,
    createdAt: new Date(Date.now() - 24 * 60 * 60 * 1000) // 24 hours ago
  };
  findOneStub.resolves(expiredToken);
  try {
    await validateRecoveryToken(req, res);
  } catch (error) {
    expect(error.message).to.equal(errorMessages.TOKEN_EXPIRED);
  }
});


describe("resetPassword", () => {
beforeEach(() => {
req.body = {
password: "test",
newPassword: "test1",
};
});

afterEach(() => {
sinon.restore();
});

it("should thrown an error if a recovery token is not found", async () => {
findOneStub.resolves(null);
try {
await resetPassword(req, res);
} catch (error) {
expect(error).to.exist;
expect(error.message).to.equal(errorMessages.DB_TOKEN_NOT_FOUND);
}
});
it("should throw an error if a user is not found", async () => {
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);
}
});
it("should throw an error if the passwords match", async () => {
findOneStub.resolves(mockRecoveryToken);
saveStub.resolves();
userFindOneStub = sinon
.stub(User, "findOne")
.returns(createQueryChain(mockUser, true));
try {
await resetPassword(req, res);
} catch (error) {
expect(error).to.exist;
expect(error.message).to.equal(errorMessages.DB_RESET_PASSWORD_BAD_MATCH);
}
});
it("should return a user without password if successful", async () => {
findOneStub.resolves(mockRecoveryToken);
saveStub.resolves();
userFindOneStub = sinon
.stub(User, "findOne")
.returns(createQueryChain(mockUser)) // First call will resolve to mockUser
.onSecondCall()
.returns(createQueryChain(mockUserWithoutPassword));
const result = await resetPassword(req, res);
expect(result).to.deep.equal(mockUserWithoutPassword);
});
});
});