Skip to content

Commit b0488db

Browse files
authored
Merge pull request #41 from kimong1/newMailgun
#16: fixes mailer and test
2 parents 80462fd + 932ea20 commit b0488db

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

services/mailer.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const mailgun = require('mailgun-js');
2+
const logger = require('../lib/log')(__filename)
3+
require('dotenv').config()
4+
5+
const mg = mailgun({apiKey: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN});
6+
7+
const mgModule = {}
8+
9+
mgModule.sendConfirmationEmail = (receiver, token) => {
10+
const link = `https://learndatabases.dev/emailConfirmation/${token}`
11+
const data = {
12+
from: 'admin@learndatabases.dev',
13+
to: receiver,
14+
subject: 'Congratulations!',
15+
text: 'Welcome to C0D3',
16+
html: `
17+
<h1> Confirm your Email </h1>
18+
<p>
19+
<a href="${link}">Click Here</a>
20+
</p>
21+
<p> Or visit this link: <a href="${link}">${link}</a></p>
22+
`
23+
};
24+
return mg.messages().send(data).then((returnedData) => {
25+
logger.info('Confirmation Email successfully sent', returnedData)
26+
}).catch((err) => {
27+
logger.error('Confirmation Email Error:',err)
28+
return err
29+
})
30+
}
31+
32+
module.exports = mgModule

services/mailer.test.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
jest.mock('../lib/log')
2+
const logGen = require('../lib/log')
3+
const logger = {
4+
info: jest.fn(),
5+
error: jest.fn()
6+
}
7+
logGen.mockReturnValue(logger)
8+
9+
jest.mock('mailgun-js')
10+
const mailgun = require('mailgun-js');
11+
const messages = {}
12+
mailgun.mockImplementation(() => {
13+
return {
14+
messages: () => {
15+
return messages
16+
}
17+
}
18+
})
19+
20+
const email = require('./mailer');
21+
22+
describe('Test mailgun', ()=>{
23+
beforeEach(() => {
24+
jest.clearAllMocks()
25+
})
26+
27+
it('should test if mocksend and mailgun is called', async () => {
28+
messages.send = jest.fn().mockReturnValue(Promise.resolve('hello'))
29+
await email.sendConfirmationEmail('paul@github.com', 'token123')
30+
expect(messages.send).toHaveBeenCalledTimes(1)
31+
expect(messages.send.mock.calls[0][0]).toMatchSnapshot()
32+
expect(logger.info).toHaveBeenCalledTimes(1)
33+
expect(logger.info.mock.calls[0][0]).toEqual('Confirmation Email successfully sent')
34+
})
35+
36+
it('should call logger.error when function is called with invalid argument', async () => {
37+
messages.send = jest.fn().mockReturnValue(Promise.reject('rejected'))
38+
await email.sendConfirmationEmail(null, null)
39+
expect(logger.error).toHaveBeenCalledTimes(1)
40+
expect(logger.error.mock.calls[0][0]).toEqual('Confirmation Email Error:')
41+
})
42+
43+
})

0 commit comments

Comments
 (0)