Skip to content
Merged
Show file tree
Hide file tree
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
32 changes: 32 additions & 0 deletions services/mailer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const mailgun = require('mailgun-js');
const logger = require('../lib/log')(__filename)
require('dotenv').config()

const mg = mailgun({apiKey: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN});

const mgModule = {}

mgModule.sendConfirmationEmail = (receiver, token) => {
const link = `https://learndatabases.dev/emailConfirmation/${token}`
const data = {
from: 'admin@learndatabases.dev',
to: receiver,
subject: 'Congratulations!',
text: 'Welcome to C0D3',
html: `
<h1> Confirm your Email </h1>
<p>
<a href="${link}">Click Here</a>
</p>
<p> Or visit this link: <a href="${link}">${link}</a></p>
`
};
return mg.messages().send(data).then((returnedData) => {
logger.info('Confirmation Email successfully sent', returnedData)
}).catch((err) => {
logger.error('Confirmation Email Error:',err)
return err
})
}

module.exports = mgModule
43 changes: 43 additions & 0 deletions services/mailer.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
jest.mock('../lib/log')
const logGen = require('../lib/log')
const logger = {
info: jest.fn(),
error: jest.fn()
}
logGen.mockReturnValue(logger)

jest.mock('mailgun-js')
const mailgun = require('mailgun-js');
const messages = {}
mailgun.mockImplementation(() => {
return {
messages: () => {
return messages
}
}
})

const email = require('./mailer');

describe('Test mailgun', ()=>{
beforeEach(() => {
jest.clearAllMocks()
})

it('should test if mocksend and mailgun is called', async () => {
messages.send = jest.fn().mockReturnValue(Promise.resolve('hello'))
await email.sendConfirmationEmail('paul@github.com', 'token123')
expect(messages.send).toHaveBeenCalledTimes(1)
expect(messages.send.mock.calls[0][0]).toMatchSnapshot()
expect(logger.info).toHaveBeenCalledTimes(1)
expect(logger.info.mock.calls[0][0]).toEqual('Confirmation Email successfully sent')
})

it('should call logger.error when function is called with invalid argument', async () => {
messages.send = jest.fn().mockReturnValue(Promise.reject('rejected'))
await email.sendConfirmationEmail(null, null)
expect(logger.error).toHaveBeenCalledTimes(1)
expect(logger.error.mock.calls[0][0]).toEqual('Confirmation Email Error:')
})

})