Ruben's Blog | Ռուբենի Բլոգը
🔙 ..Testing email sending with Jest, nodemailer, Node and TypeScript 📩
Ever since I started to do Test-driven development(TDD) I am encountered various issues regarding which I cannot find definitive solutions, so I will write my own.
Last time, I couldn’t make nodemailer to work with jest.
So imagine you have this REST API endpoint under /api/send-email
you want to test.
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: 'smtp.host.com',
port: 465,
secure: true,
auth: {
user: 'REPLACE-WITH-YOUR-ALIAS@YOURDOMAIN.COM',
pass: 'REPLACE-WITH-YOUR-GENERATED-PASSWORD',
},
});
const sendEmail = async (req: Request, res: Response) => {
const email = 'some-email@mail.com';
try {
await transporter.sendMail({
from: `"Test email content" <${process.env.EMAIL_URL}>`,
to: email,
subject: 'Hello from test email.',
text: `This is a test email, thank you.`,
html: `
This is a test email,
<br>
thank you.
`,
});
res.status(200).send({ message: 'Please check your email.' });
} catch (err) {
res.status(400).send({ error: { message: 'Something went wrong.' } });
}
};
Now let’s test it with Jest.
import { htmlToText } from 'html-to-text'; // in order to test html content
// for some js reason this doesn't work with let
var sendMailMock: jest.Mock;
// mocking nodemailer
jest.mock('nodemailer', () => {
return {
__esModule: true, // this line makes it work!
default: {
createTransport: () => {
// be sure to use promise
sendMailMock = jest.fn((mail: Mail) => Promise.resolve(mail));
return { sendMail: sendMailMock };
},
},
};
});
beforeEach(() => {
sendMailMock.mockClear();
});
describe('{email test}', () => {
test('POST /api/send-email should send an email', async () => {
const email = 'some-email@mail.com'
const body = {};
const response = await request(app)
.post('/api/send-email')
.send(body);
expect(response.status).toBe(200);
// checking the argument that was passed to the sendMail function
const [args] = sendMailMock.mock.calls[0] as any;
expect(sendMailMock).toHaveBeenCalled();
expect(args.to).toBe(email);
expect(args.subject).toBe('Hello from test email.');
const htmlText = htmlToText(args.html);
expect(htmlText).not.toBe('');
const emailContaingTexts = [
'This is a test email,',
'thank you.'
];
emailContaingTexts.forEach((emailContaingText) =>
expect(htmlText).toContain(emailContaingText),
);
});
});
This way you can test any aspect of email sending.
Please give me feedback, comment on whatever you think about my blog post, and help me improve. ❤️
Blog Menu
- 💼 hire my consultancy
- ℹ️ about me
- 📰 rss
- 🛸 a young blog
- 📝 blog
- 2024-12-13
Rushing the Process Doesn't Help ⌛️
I’ve started too late, because of that I have more knowledge from the field. I have been learning these past 4 years, but starting something by ...
- 2024-12-12
Hello world Again 🗺️
Long time no blog. WTF is happening? Writing a blog is too important for me, when I don’t write a blog I don’t analyze as much. Sometimes ...
- 2024-11-15
What Would You Do if It Wasn't for Money? 💱
What is money? For some it’s freedom. Freedom of choice. For me it’s an equivalent of “ability”. It’s like the magic wan...
- 2024-11-12
First, Rewrite🐇
I start to see patterns. I start to see how people work. Not sure how deep I see. I don’t want to exploit people. I don’t want to MAKE peo...
- 2024-11-11
It's Not About Sales 💆🏻
For me it’s always about how can I help people, if I can’t or if my help is insufficient I would not push. I will push to know the reason ...
- 2024-11-09
Push Push Push Breathe 🌬️
Am I pushing enough? Am I breathing enough? I do :) There is never enough, there is always enough. Having multiple heats it’s hard to find a bal...
- 2024-11-08
Am I Productive? 🧨
Do you feel I’m productive? Are you productive? Is productive about fast results? Is productive about the process? I’m not sure anymore, b...
- 2024-11-07
One Week Later ⌛️
Last week was awful, I didn’t have time to breathe. This week is not much better. But we have progress. I have about 3k impressions in 2 days on...
- 2024-10-28
Engineering Solution to Every Problem ⚙️
As an engineer, I strive to find engineering solutions to every problem surrounding me, engineering doesn’t mean technical in this case. There a...
- 2024-10-27
I'm Going to Invest in Podcasting More 🎤
Podcasting is discovery It’s listening to so many familiar and different ideas and being able to ask questions, where people can answer you live...
- See all...
- 🔗 links