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 me
- ℹ️ about me
- 📰 rss
- 🛸 a young blog
- 📝 blog
- 2024-10-19
The Meaning 🌬️
I wrote about this again, but investing time in meaningful connections is crucial. It’s not just spending; it’s a real investment. You can...
- 2024-10-18
Complexity in Multi-model Architectures 📊
I can move from cities and even to countries with a single backpack and or a single hanger with a couple of clothes, be able to attend the event, and ...
- 2024-10-18
Buying Problems 📛
I must always remember that buying into any relationship, be that business, employment, or personal once, you are always buying problems first. It&rsq...
- 2024-10-16
Every Company Is Different 🤦🏻♂️
Doing the podcasts I talk to different friends from tech and other industries. There are so many approaches, and so many different opinions, there is ...
- 2024-10-15
Lazy Art 🎨
Art is something you do more not less, but what if you generate NFTS, is it lazy art? You do more but with code. Are you making more art? If you creat...
- 2024-10-14
Tribute to Mothers Part 3? 🤱🏻
Again I’m alone, this is hard. Though I don’t consider myself a passive father, being 2 parents is a bit much, and it’s hard as much...
- 2024-10-13
Weekends ⭐️
Yesterday, I spent the day picking pears and sleeping. Today, I spent the day caring for the baby and trying to rest; I can’t rest with a small ...
- 2024-10-12
I Fell Out of the Internet for Today 🌐
My phone is broken and My current phone is a Banana Nokia. I spent half of the day sleeping and another half picking pears from the ground and cooking...
- 2024-10-11
Life Lessons 🎒
My phone broke down so I couldn’t post shorts on YouTube, today I spent time running Android on my laptop. Well, Weydroid ran with a plain Andro...
- 2024-10-10
Podcasting Is Fun 🪃
But it’s hard work.:) You need to try to engage with the person you are doing a podcast with! It’s good but hard. Tomorrow I don’t h...
- See all...
- 🔗 links