Skip to content

Commit

Permalink
Merge pull request #1114 from OneCommunityGlobal/jordy_add_emailContr…
Browse files Browse the repository at this point in the history
…ollerUnitTests

Jordy add email controller unit tests
  • Loading branch information
one-community authored Oct 24, 2024
2 parents fd7d56e + e697b05 commit 16b2b83
Show file tree
Hide file tree
Showing 7 changed files with 253 additions and 0 deletions.
23 changes: 23 additions & 0 deletions requirements/emailController/addNonHgnEmailSubscription.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Add Non-HGN Email Subscription Function

## Negative Cases

1.**Returns error 400 if `email` field is missing from the request**
- Ensures that the function checks for the presence of the `email` field in the request body and responds with a `400` status code if it's missing.

2.**Returns error 400 if the provided `email` already exists in the subscription list**
- This case checks that the function responds with a `400` status code and a message indicating that the email is already subscribed.

3.**Returns error 500 if there is an internal error while checking the subscription list**
- Covers scenarios where there's an issue querying the `EmailSubscriptionList` collection for the provided email (e.g., database connection issues).

4.**Returns error 500 if there is an error sending the confirmation email**
- This case handles any issues that occur while calling the `emailSender` function, such as network errors or service unavailability.

## Positive Cases

1.**Returns status 200 when a new email is successfully subscribed**
- Ensures that the function successfully creates a JWT token, constructs the email, and sends the subscription confirmation email to the user.

2.**Successfully sends a confirmation email containing the correct link**
- Verifies that the generated JWT token is correctly included in the confirmation link sent to the user in the email body.
18 changes: 18 additions & 0 deletions requirements/emailController/confirmNonHgnEmailSubscription.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Confirm Non-HGN Email Subscription Function Tests

## Negative Cases
1.**Returns error 400 if `token` field is missing from the request**
- (Test: `should return 400 if token is not provided`)

2.**Returns error 401 if the provided `token` is invalid or expired**
- (Test: `should return 401 if token is invalid`)

3.**Returns error 400 if the decoded `token` does not contain a valid `email` field**
- (Test: `should return 400 if email is missing from payload`)

4.**Returns error 500 if there is an internal error while saving the new email subscription**

## Positive Cases
1.**Returns status 200 when a new email is successfully subscribed**

2.**Returns status 200 if the email is already subscribed (duplicate email)**
10 changes: 10 additions & 0 deletions requirements/emailController/removeNonHgnEmailSubscription.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Remove Non-HGN Email Subscription Function Tests

## Negative Cases
1.**Returns error 400 if `email` field is missing from the request**
- (Test: `should return 400 if email is missing`)

2.**Returns error 500 if there is an internal error while deleting the email subscription**

## Positive Cases
1.**Returns status 200 when an email is successfully unsubscribed**
10 changes: 10 additions & 0 deletions requirements/emailController/sendEmail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Send Email Function

## Negative Cases

1.**Returns error 400 if `to`, `subject`, or `html` fields are missing from the request**
2.**Returns error 500 if there is an internal error while sending the email**

## Positive Cases

1.**Returns status 200 when email is successfully sent with `to`, `subject`, and `html` fields provided**
26 changes: 26 additions & 0 deletions requirements/emailController/sendEmailToAll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Send Email to All Function

## Negative Cases

1.**Returns error 400 if `subject` or `html` fields are missing from the request**
- The request should be rejected if either the `subject` or `html` content is not provided in the request body.

2.**Returns error 500 if there is an internal error while fetching users**
- This case covers scenarios where there's an error fetching users from the `userProfile` collection (e.g., database connection issues).

3.**Returns error 500 if there is an internal error while fetching the subscription list**
- This case covers scenarios where there's an error fetching emails from the `EmailSubcriptionList` collection.

4.**Returns error 500 if there is an error sending emails**
- This case handles any issues that occur while calling the `emailSender` function, such as network errors or service unavailability.

## Positive Cases

1.**Returns status 200 when emails are successfully sent to all active users**
- Ensures that the function sends emails correctly to all users meeting the criteria (`isActive` and `EmailSubcriptionList`).

2.**Returns status 200 when emails are successfully sent to all users in the subscription list**
- Verifies that the function sends emails to all users in the `EmailSubcriptionList`, including the unsubscribe link in the email body.

3.**Combines user and subscription list emails successfully**
- Ensures that the function correctly sends emails to both active users and the subscription list without issues.
20 changes: 20 additions & 0 deletions requirements/emailController/updateEmailSubscription.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Update Email Subscriptions Function

## Negative Cases

1.**Returns error 400 if `emailSubscriptions` field is missing from the request**
- This ensures that the function checks for the presence of the `emailSubscriptions` field in the request body and responds with a `400` status code if it's missing.

2.**Returns error 400 if `email` field is missing from the requestor object**
- Ensures that the function requires an `email` field within the `requestor` object in the request body and returns `400` if it's absent.

3.**Returns error 404 if the user with the provided `email` is not found**
- This checks that the function correctly handles cases where no user exists with the given `email` and responds with a `404` status code.

4.**Returns error 500 if there is an internal error while updating the user profile**
- Covers scenarios where there's a database error while updating the user's email subscriptions.

## Positive Cases

1.**Returns status 200 and the updated user when email subscriptions are successfully updated**
- Ensures that the function updates the `emailSubscriptions` field for the user and returns the updated user document along with a `200` status code.
146 changes: 146 additions & 0 deletions src/controllers/emailController.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
const { mockReq, mockRes, assertResMock } = require('../test');
const emailController = require('./emailController');
const jwt = require('jsonwebtoken');
const userProfile = require('../models/userProfile');


jest.mock('jsonwebtoken');
jest.mock('../models/userProfile');
jest.mock('../utilities/emailSender');




const makeSut = () => {
const {
sendEmail,
sendEmailToAll,
updateEmailSubscriptions,
addNonHgnEmailSubscription,
removeNonHgnEmailSubscription,
confirmNonHgnEmailSubscription,
} = emailController;
return {
sendEmail,
sendEmailToAll,
updateEmailSubscriptions,
addNonHgnEmailSubscription,
removeNonHgnEmailSubscription,
confirmNonHgnEmailSubscription,
};
};
describe('emailController Controller Unit tests', () => {
afterEach(() => {
jest.clearAllMocks();
});

describe('sendEmail function', () => {
test('should send email successfully', async () => {
const { sendEmail } = makeSut();
const mockReq = {
body: {
to: '[email protected]',
subject: 'Test Subject',
html: '<p>Test Body</p>',
},
};
const response = await sendEmail(mockReq, mockRes);
assertResMock(200, 'Email sent successfully', response, mockRes);
});
});

describe('updateEmailSubscriptions function', () => {
test('should handle error when updating email subscriptions', async () => {
const { updateEmailSubscriptions } = makeSut();


userProfile.findOneAndUpdate = jest.fn();

userProfile.findOneAndUpdate.mockRejectedValue(new Error('Update failed'));

const mockReq = {
body: {
emailSubscriptions: ['subscription1', 'subscription2'],
requestor: {
email: '[email protected]',
},
},
};

const response = await updateEmailSubscriptions(mockReq, mockRes);

assertResMock(500, 'Error updating email subscriptions', response, mockRes);
});
});


describe('confirmNonHgnEmailSubscription function', () => {
afterEach(() => {
jest.clearAllMocks();
});

beforeAll(() => {
jwt.verify = jest.fn();
});

test('should return 400 if token is not provided', async () => {
const { confirmNonHgnEmailSubscription } = makeSut();

const mockReq = { body: {} };
const response = await confirmNonHgnEmailSubscription(mockReq, mockRes);

assertResMock(400, 'Invalid token', response, mockRes);
});

test('should return 401 if token is invalid', async () => {
const { confirmNonHgnEmailSubscription } = makeSut();
const mockReq = { body: { token: 'invalidToken' } };

jwt.verify.mockImplementation(() => {
throw new Error('Token is not valid');
});

await confirmNonHgnEmailSubscription(mockReq, mockRes);

expect(mockRes.status).toHaveBeenCalledWith(401);
expect(mockRes.json).toHaveBeenCalledWith({
errors: [
{ msg: 'Token is not valid' },
],
});
});


test('should return 400 if email is missing from payload', async () => {
const { confirmNonHgnEmailSubscription } = makeSut();
const mockReq = { body: { token: 'validToken' } };

// Mocking jwt.verify to return a payload without email
jwt.verify.mockReturnValue({});

const response = await confirmNonHgnEmailSubscription(mockReq, mockRes);

assertResMock(400, 'Invalid token', response, mockRes);
});





});
describe('removeNonHgnEmailSubscription function', () => {
afterEach(() => {
jest.clearAllMocks();
});

test('should return 400 if email is missing', async () => {
const { removeNonHgnEmailSubscription } = makeSut();
const mockReq = { body: {} };

const response = await removeNonHgnEmailSubscription(mockReq, mockRes);

assertResMock(400, 'Email is required', response, mockRes);
});
});

});

0 comments on commit 16b2b83

Please sign in to comment.