在 Jest 和 Node.js 中做邮件测试

· 5 分钟阅读 · QuickInbox 团队

  • Jest
  • Node.js
  • 邮件测试

mock 邮件发送器只能证明你的代码调用了 send()。真实邮箱才能证明邮件到达了,并且主题、链接和验证码都正确。下面介绍如何把它加到 Jest 中。

辅助函数

对于在 CI 中运行的集成测试,Business API 的私有邮箱效果最好。设置 QI_KEY 和 QI_NAMESPACE,然后:

// inbox.js - private test inboxes with the Business API (Node 18+)
const BASE = 'https://business.quickinbox.net';
const NS = process.env.QI_NAMESPACE;            // e.g. "acme7x"
const auth = { headers: { 'X-API-Key': process.env.QI_KEY } };

// Any tag works at once: acme7x.<tag>@quickinbox.net
export function newAddress(prefix = 'test') {
  const tag = `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
  return { tag, address: `${NS}.${tag}@quickinbox.net` };
}

export async function waitForEmail(tag, { timeoutMs = 60_000, subject = '' } = {}) {
  const since = Math.floor(Date.now() / 1000) - 60;
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const res = await fetch(`${BASE}/api/business/mail?namespace=${NS}&since=${since}&limit=50`, auth);
    if (res.ok) {
      const { messages } = await res.json();
      const hit = messages.find((m) => m.to === `${NS}.${tag}` && m.subject.includes(subject));
      if (hit) return hit; // id, to, from, subject, text, html, spam, receivedAt
    }
    await new Promise((r) => setTimeout(r, 2000));
  }
  throw new Error(`No email for ${tag} within ${timeoutMs} ms`);
}

因为命名空间下的任何标签都是一个新地址,你不需要创建调用,并行的 Jest 进程也永远不会共用邮箱。

测试欢迎邮件

// welcome.test.js
import { newAddress, waitForEmail } from './inbox.js';
import { createUser } from '../src/users.js'; // your code that sends the email

jest.setTimeout(90_000);

test('sends a welcome email with a working dashboard link', async () => {
  const { tag, address } = newAddress('welcome');
  await createUser({ email: address, name: 'Test User' });

  const email = await waitForEmail(tag, { subject: 'Welcome' });
  expect(email.subject).toBe('Welcome to Acme, Test User');
  expect(email.html).toContain('https://app.example.com/dashboard');
  expect(email.html).not.toContain('localhost');
});

测试重置验证码

test('password reset email has a 6-digit code', async () => {
  const { tag, address } = newAddress('reset');
  await requestPasswordReset(address);
  const email = await waitForEmail(tag, { subject: 'Reset' });
  expect(email.text).toMatch(/\b\d{6}\b/);
});

保持单元测试快速

每次保存都运行的单元测试继续用 mock。把这些真实邮箱测试作为单独的 Jest 项目运行,或只在 CI 中运行,例如用 jest --selectProjects integration。

也检查送达率

Business 命名空间中的每封邮件都附带垃圾邮件评分和 SPF、DKIM、DMARC 结果。加上 expect(email.spam.score).toBeGreaterThan(70) 就能发现发件配置的问题。参见测试邮件模板。

相关指南

获取私有邮箱:QuickInbox Business API 提供每月 5,000 封邮件的免费套餐,付费套餐每月 $9 起。创建免费账户或阅读 API 文档。

← 全部文章