Node.js › Email & Notifications

How would you test that a Node.js application correctly sends emails without actually sending real emails during automated tests?

Intermediate

Answer

Rather than hitting a real email provider during tests (slow, costly, and dependent on external network availability), tests typically mock the email-sending function or transport entirely, asserting that it was called with the expected arguments (recipient, subject, relevant content) -- some teams additionally use a tool like Ethereal Email or Mailhog, a fake SMTP server for local/CI testing that captures sent emails for inspection without any real delivery.
jest.mock('../emailService');

test('sends a welcome email on registration', async () => {
  await registerUser({ email: 'test@example.com' });
  expect(emailService.sendWelcomeEmail).toHaveBeenCalledWith(
    expect.objectContaining({ email: 'test@example.com' })
  );
});
Real-world example A test suite for a registration flow mocks the email service entirely, verifying only that sendWelcomeEmail was called with the correct user data, avoiding any dependency on network access or a real (or even fake) SMTP server during fast, reliable unit tests.

Common follow-ups: What's the tradeoff between mocking the email function versus using a fake SMTP server like Mailhog for integration-level testing?;How would you write an end-to-end test that verifies an actual email's content and formatting render correctly?