DEV Community

QuickInbox
QuickInbox

Posted on Originally published at quickinbox.net AI-assisted

How to test email verification in Playwright

Most signup tests stop at "the form submitted". The part that actually breaks in production is the email: the template, the link, the code, the delivery. This guide shows how to test the whole flow in Playwright with a real inbox that your test creates on the fly.

Why mocking the email isn't enough

If you stub out your email provider, your test proves the button works. It doesn't prove that the email was sent, that the link inside it points to the right domain, or that the code in the email matches what your backend expects. Those are exactly the bugs real users hit.

The fix is to give every test its own disposable address, let your app send a real email to it, and read that email from the test. QuickInbox has a free JSON API for this. It needs no signup and no API key.

The flow

  1. Create a fresh address with POST /api/generate.
  2. Fill your signup form with that address.
  3. Poll GET /api/inbox/:local until the verification email arrives.
  4. Pull the link or the code out of the email and finish the flow.

Step 1: a small inbox helper

Put this in tests/helpers/inbox.ts. It uses the built-in fetch in Node 18 and newer, so there's nothing to install.

// tests/helpers/inbox.ts
const BASE = 'https://quickinbox.net';

export type Email = {
  id: string;
  from: string;
  subject: string;
  text: string;
  html: string;
  receivedAt: number;
};

/** Creates a new disposable address that lives for `minutes` (5-30). */
export async function createInbox(minutes = 10) {
  const res = await fetch(`${BASE}/api/generate`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ minutes }),
  });
  if (!res.ok) throw new Error(`createInbox failed: ${res.status} ${await res.text()}`);
  const { address } = (await res.json()) as { address: string };
  return { address, local: address.split('@')[0] };
}

/** Polls the inbox until an email matching `subject` arrives, or times out. */
export async function waitForEmail(
  local: string,
  { subject = '', timeoutMs = 60_000, intervalMs = 2_000 } = {},
): Promise<Email> {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const res = await fetch(`${BASE}/api/inbox/${local}`);
    if (res.ok) {
      const { messages } = (await res.json()) as { messages: Email[] };
      const hit = messages.find((m) => m.subject.includes(subject));
      if (hit) return hit;
    }
    await new Promise((r) => setTimeout(r, intervalMs));
  }
  throw new Error(`No email with subject "${subject}" within ${timeoutMs} ms`);
}

/** Returns the first link in the email whose URL matches `pattern`. */
export function extractLink(email: Email, pattern: RegExp) {
  const links = [...(email.html || '').matchAll(/href="([^"]+)"/g)]
    .map((m) => m[1].replace(/&amp;/g, '&'));
  const link = links.find((url) => pattern.test(url));
  if (!link) throw new Error(`No link matching ${pattern} in "${email.subject}"`);
  return link;
}

/** Returns the first 4-8 digit code in the email text (an OTP). */
export function extractCode(email: Email) {
  const match = (email.text || '').match(/\b(\d{4,8})\b/);
  if (!match) throw new Error(`No code found in "${email.subject}"`);
  return match[1];
}
Enter fullscreen mode Exit fullscreen mode

Step 2: test a verification link

Here's a full test for a signup that sends a "Verify your email" link. Change the labels and the URL pattern to match your app.

// tests/signup.spec.ts
import { test, expect } from '@playwright/test';
import { createInbox, waitForEmail, extractLink } from './helpers/inbox';

test('a new user can sign up and verify their email', async ({ page }) => {
  test.setTimeout(90_000); // leave room for the email to arrive

  const inbox = await createInbox();

  await page.goto('/signup');
  await page.getByLabel('Email').fill(inbox.address);
  await page.getByLabel('Password').fill('Correct-Horse-42');
  await page.getByRole('button', { name: 'Create account' }).click();
  await expect(page.getByText('Check your inbox')).toBeVisible();

  const email = await waitForEmail(inbox.local, { subject: 'Verify' });
  const link = extractLink(email, /\/verify/);

  await page.goto(link);
  await expect(page.getByText('Your email is verified')).toBeVisible();
});
Enter fullscreen mode Exit fullscreen mode

Step 3: or test a one-time code (OTP)

If your app emails a 6-digit code instead of a link, read the code and type it in:

const email = await waitForEmail(inbox.local, { subject: 'code' });
const code = extractCode(email);

await page.getByLabel('Verification code').fill(code);
await page.getByRole('button', { name: 'Verify' }).click();
await expect(page).toHaveURL(/\/dashboard/);
Enter fullscreen mode Exit fullscreen mode

Tips that save you flaky runs

  • Give the email time. Most providers deliver in a few seconds, but set the test timeout to 60-90 seconds so a slow send doesn't fail the build.
  • One address per test. A fresh address means no old emails to confuse the match, and tests can run in parallel.
  • Mind the rate limit. The free API allows about 10 new addresses per minute per IP. For big parallel suites, create one address per worker, or use the Business API below.
  • Match on the subject. If your app sends a welcome email and a verification email, the subject filter picks the right one.
  • Use test data only. A free temporary inbox can be read by anyone who knows its address, so never send real customer data or secrets to it.

When you need private inboxes

The free API is perfect for getting started. For a team or CI at scale, the QuickInbox Business API gives you private namespaces that only your API key can read, webhooks that fire the moment an email lands (no polling), your own custom domains, and an MCP server so AI coding agents can read test emails too. See the Business API docs for the full reference.

Try it now, no signup: the free endpoints above are documented on the temporary email API page. You can also open a disposable inbox in your browser to watch emails arrive while you write your test.


Originally published on the QuickInbox blog.

Top comments (0)