diff --git a/services/mailer.js b/services/mailer.js new file mode 100644 index 00000000..ffcdd344 --- /dev/null +++ b/services/mailer.js @@ -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: ` +

Confirm your Email

+

+ Click Here +

+

Or visit this link: ${link}

+ ` + }; + 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 \ No newline at end of file diff --git a/services/mailer.test.js b/services/mailer.test.js new file mode 100644 index 00000000..de7964eb --- /dev/null +++ b/services/mailer.test.js @@ -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:') + }) + +})