How to test email OTP and 2FA codes
A 6-digit code by email protects signups and logins in many apps. It's also easy to break with a template change, a timezone bug or a cache.
The happy path
import { test, expect } from '@playwright/test';
import { createInbox, waitForEmail, extractCode } from './helpers/inbox';
test('login with an email code', async ({ page }) => {
test.setTimeout(90_000);
const inbox = await createInbox();
await signUp(page, inbox.address); // your own helper
await page.goto('/login');
await page.getByLabel('Email').fill(inbox.address);
await page.getByRole('button', { name: 'Send code' }).click();
const email = await waitForEmail(inbox.local, { subject: 'code' });
await page.getByLabel('Code').fill(extractCode(email));
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByText('Dashboard')).toBeVisible();
});The helpers are in email verification in Playwright.
Edge cases worth a test
- Expiry: an old code is refused.
- Reuse: a code works only once.
- Resend: after "send a new code", the old code stops working (if that's your rule).
- Wrong codes: after a few wrong tries the form locks or slows down.
- Two emails close together: your test picks the newest code, not the first one in the inbox.
- Format: the code in the email matches what the form accepts (length, leading zeros).
Reading the right code
If your email contains other numbers (an order number, a year in the footer), use a tighter pattern than "any 4 to 8 digits", for example /code is (\d{6})/, and match on the subject.
SMS codes too?
Many apps offer SMS as a second channel. The same account can give your tests a real US number. See SMS OTP in Playwright. AI agents can run email code tests too: MCP server for OTP testing.
Related guides
- How to test emails in GitHub Actions
- How to test transactional email templates: links, content and spam score
- Disposable email API for developers
- How to receive incoming email by webhook
- Email testing API overview
Try it now: the free endpoints above need no signup and are documented on the temporary email API page. For private inboxes, webhooks and CI at scale, the QuickInbox Business API has a free plan with 5,000 emails a month.