Jestbeginner
Jest Email Service Test
Unit/integration test for email service with Jest
Jest Email Service Test (typescript)typescript
// src/services/email.ts
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
export async function sendWelcomeEmail(to: string, name: string) {
return resend.emails.send({
from: 'hello@yourapp.com',
to,
subject: `Welcome to YourApp, ${name}!`,
html: `
<h1>Welcome, ${name}!</h1>
<p>Thanks for signing up. Here's how to get started:</p>
<a href="https://yourapp.com/dashboard">Go to Dashboard</a>
`,
});
}
// tests/email.test.ts
import { sendWelcomeEmail } from '../src/services/email';
const PLOP_API_URL = 'https://api.plop.email/v1';
const PLOP_API_KEY = process.env.PLOP_API_KEY!;
async function fetchEmail(to: string) {
const response = await fetch(
`${PLOP_API_URL}/messages/latest?to=${encodeURIComponent(to)}`,
{
headers: { Authorization: `Bearer ${PLOP_API_KEY}` },
}
);
return response.json();
}
describe('Email Service', () => {
it('sends welcome email with correct content', async () => {
const testEmail = `welcome+${Date.now()}@in.plop.email`;
const userName = 'Test User';
// Send the email
const result = await sendWelcomeEmail(testEmail, userName);
expect(result.error).toBeUndefined();
// Wait for delivery
await new Promise((r) => setTimeout(r, 2000));
// Fetch from plop
const email = await fetchEmail(testEmail);
// Verify content
expect(email.subject).toBe(`Welcome to YourApp, ${userName}!`);
expect(email.htmlContent).toContain(`Welcome, ${userName}!`);
expect(email.htmlContent).toContain('Go to Dashboard');
expect(email.htmlContent).toContain('https://yourapp.com/dashboard');
});
it('handles special characters in name', async () => {
const testEmail = `special+${Date.now()}@in.plop.email`;
const userName = "O'Brien & Co.";
await sendWelcomeEmail(testEmail, userName);
await new Promise((r) => setTimeout(r, 2000));
const email = await fetchEmail(testEmail);
// Verify HTML escaping
expect(email.htmlContent).toContain("O'Brien");
expect(email.subject).toContain("O'Brien");
});
});How It Works
1
Real Email Sending
Unlike mocking, this actually sends emails through your email service (Resend in this example) and verifies they arrive correctly.
2
Content Verification
We verify the exact subject line, personalization (name), and links are present in the delivered email.
3
Edge Cases
The second test checks that special characters are handled correctly—important for preventing XSS and display issues.
4
Integration Testing
This pattern tests your complete email pipeline: your code → email service → actual delivery.