The basic steps for testing email OTPs end to end are to trigger OTP generation and delivery to a unique test inbox address, wait for the email through an API instead of a fixed-length sleep, extract the OTP from the plain-text version of the email body with a regular expression, and submit it in the same test. You’ll also want to test all of the scenarios where OTP verification should fail: an incorrect OTP, an expired OTP, an OTP that’s already been used, an OTP invalidated because a new one was requested, and too many unsuccessful login attempts.
This guide covers what OTP testing includes, the test cases worth automating, how to extract codes reliably in JavaScript, Python and Java, a complete Playwright suite you can adapt, CI setup, and notes for Supabase and Clerk. We’ll use testmail.app in our examples, but these testing strategies will work regardless of which email testing setup you use. With testmail.app every email address under your namespace is a valid inbox, and one API request waits for the email to arrive.
Updated November 2026 with new Playwright test examples (single-use enforcement, resend invalidation, account lockout, OTP delivery time), API test examples (resend cooldown enforcement, OTPs tied to email addresses, protection against account enumeration attacks), examples of extracting OTPs from emails in JavaScript, Python and Java, Cypress examples moved to the Cypress 16 pattern, and notes on testing Supabase and Clerk OTP implementations.
What is an OTP?
One-time passwords (OTPs) are short codes that verify that the person logging in to an account has access to a device or email address. They’re called one-time passwords because they can only be used once and are only valid for a short amount of time (30 seconds to 10 minutes, typically). There are three types of OTPs:
| Type | How the code is made | Where it usually shows up |
|---|---|---|
| TOTP, time-based (RFC 6238) | A shared secret plus the current time, in 30-second steps | Authenticator apps; the server never sends it |
| HOTP, counter-based (RFC 4226) | A shared secret plus a counter that moves on each use | Hardware tokens |
| Random | A random number generated and stored (ideally hashed) by the server | Email and SMS codes |
Email OTPs are almost always randomly generated codes that the application stores (along with an expiration date) and emails to the user. It’s the expiration date and delivery that make OTPs a little tricky to test, since a properly generated OTP may not make it to the user in time (or at all), or may be hard to find in the email. One other common email-based authentication flow uses magic links instead of one-time passwords. Check out the magic link testing guide to learn how to test those.

What OTP testing covers
You can unit test OTP generation, but that’s only testing a small piece of the OTP authentication flow. End-to-end tests check that the code is generated and stored, the email reaches the correct email address within the OTP’s expiration window, the OTP is easily identifiable within the email, and your application accepts a valid, unexpired OTP once and rejects it in every other case.
It helps to map the states before writing tests. A code that has been issued has exactly one good outcome and four ways it must be refused:

The states of an email OTP · one success, four rejections
Each box is a test. Of these, “OTP resend should invalidate previous OTPs” is the most commonly forgotten one. When a user asks for a new code, the old one should stop working, and that’s easy to break when the resend path is changed.

Four ways to test email OTPs
| Approach | How it works | What it proves | What it misses |
|---|---|---|---|
| Manual | Trigger the flow, open a real inbox, type the code | Quick feedback while you build | Doesn't scale, can't run in CI, edge cases get tested inconsistently |
| API-only | Call your request and verify endpoints; read the code from the database or a test hook | Generation, expiry, single use and limits, in milliseconds | Delivery, the email's content, the UI |
| End to end with a test inbox | The app emails a unique test address; the test reads the email by API and types the code | The whole path, including delivery and extraction | Takes seconds per email, and the test environment must send real email |
| Provider test codes | The auth provider accepts a fixed code for test identities and sends nothing (Clerk's 424242, for example) | Your code-entry screen and session handling | The email entirely; never enable it in production |
In practice, most teams opt for a mix of the two: they write API-level tests for most test cases, and only end-to-end test a smaller subset that proves a real email arrives with a code that works. The latter is worthwhile because it can detect problems that API-only tests can’t, like misconfigured email providers, broken email templates or the OTP only being sent in the HTML version of the email. For this guide, we’ll focus on the latter: end-to-end OTP tests.

The OTP test cases to automate
| Test case | Expected result | Best level |
|---|---|---|
| A valid code on the first try | Signed in, session created | End to end |
| Time to inbox | The email arrives within your target, for example 30 seconds | End to end |
| Sender, subject and stated lifetime | Right sender and subject; "expires in 10 minutes" matches the real lifetime | End to end |
| Code in the plain-text part | The code is in text as well as the HTML, so every client shows it | End to end |
| A wrong code | Rejected with a clear message; the attempt is counted | End to end or API |
| Too many wrong codes | Locked: even the right code fails until a new one is requested or a cooldown ends | End to end or API |
| The same code twice | Rejected after the first successful use | API |
| An expired code | Rejected once the lifetime has passed | API, with a short lifetime in the test environment |
| A resend | A new code arrives and the old one is rejected | End to end |
| A second resend straight away | Refused during the cooldown, in the UI and through the API | API |
| A code used with another address | Rejected: codes belong to one address | API |
Pasted with spaces, such as 482 913 | Accepted, or a clear message; never a silent failure | End to end |
| An address with no account | The same response as a known address, so the form doesn't reveal who has an account | API |
The end-to-end rows need a real inbox; the API rows can call your endpoints directly, but they still need the code, so they read it from the test inbox too rather than from the database. That keeps the tests honest about what the user actually receives.

Get the code out of the email
All email OTP tests will have these two steps in common: wait for the next email to be sent to a unique email address, then extract the OTP from the email. If you’re using testmail.app, the address format is {namespace}.{tag}@inbox.testmail.app: changing the tag results in a new inbox. By specifying livequery=true when fetching emails, testmail.app will hold the API request until an email has arrived.
JavaScript or TypeScript
This code doesn’t have any dependencies other than fetch, which is built into Node 18 or newer, so it can be used as-is in a Playwright, Jest or Vitest test suite, or even outside of tests altogether:
// tests/otp.ts
const API = 'https://api.testmail.app/api/json';
const NAMESPACE = process.env.TESTMAIL_NAMESPACE ?? '';
const APIKEY = process.env.TESTMAIL_APIKEY ?? '';
export type Email = { subject: string; text: string; html: string; timestamp: number };
export class Inbox {
readonly tag = `otp.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
readonly address = `${NAMESPACE}.${this.tag}@inbox.testmail.app`;
private since = Date.now();
/** Waits on testmail.app's side for the next email to this inbox. */
async next(): Promise<Email> {
const params = new URLSearchParams({
apikey: APIKEY,
namespace: NAMESPACE,
tag: this.tag,
timestamp_from: String(this.since),
livequery: 'true',
});
const res = await fetch(`${API}?${params}`, { signal: AbortSignal.timeout(85_000) });
const body = await res.json();
if (body.result !== 'success') throw new Error(`testmail.app: ${body.message}`);
const emails: Email[] = body.emails;
const email = emails.reduce((a, b) => (a.timestamp <= b.timestamp ? a : b)); // oldest new email
this.since = email.timestamp + 1; // the next call waits for a newer one
return email;
}
}
/** The first six-digit number in the plain-text part. */
export function otpFrom(email: Email, pattern = /\b\d{6}\b/): string {
const code = email.text.match(pattern)?.[0];
if (!code) throw new Error(`No code matching ${pattern} in "${email.subject}"`);
return code;
}
/** A code that is guaranteed to be wrong: the right one with its last digit changed. */
export function wrongCode(code: string): string {
return code.slice(0, -1) + ((Number(code.at(-1)) + 1) % 10);
}Two interesting bits of the above code: timestamp_from makes sure that next() waits for a new email after a resend. Without this parameter, a live query will immediately return an existing matching email instead of waiting for a new one to arrive. wrongCode() makes it easier to test rejection of invalid OTPs: instead of naively sending 000000 (which might actually be a valid OTP), we derive an incorrect OTP from the actual OTP.
Regular expressions that don't break
- Six digits:
/\b\d{6}\b/is usually a good-enough regular expression for extracting them from emails. The word-boundary bits make sure we don’t match on parts of longer numbers (phone numbers, order numbers, etc.). - Read the plain-
textpart. It’s not uncommon for the HTML version to make it harder to extract OTPs using regular expressions, e.g. by putting each digit in its own HTML table cell for easier styling, or sneaking in some non-obvious spaces. A pattern that works ontextcan fail onhtml. - Letters and digits: if your OTPs contain both letters and numbers, make sure to anchor the regular expression on some text that’s guaranteed to be there, e.g. “code:”. Otherwise, a regular expression like
/\b[A-Z0-9]{8}\b/will also match on random all-caps eight-letter words, likePASSWORD. For example,/code(?:\s+is)?:?\s*([A-Z0-9]{8})\b/iwill extract the OTP from both “Code: ABCD1234” and “Your code is ABCD1234”; use the captured group. - Spaced codes like
482 913: anchor to the label as well,/code(?:\s+is)?:?\s*(\d{3}[ -]?\d{3})\b/i, and remove the space or dash from the result before entering it. Without anchoring to the label, such a regex will cheerfully extract a code from the first few digits of a phone number in your site’s footer. - Have a test that fails if your code format changes, so that if you switch from six-digit to eight-digit codes you get a useful failure (“couldn’t find a code matching ...”) instead of some baffling behaviour three steps later.
Python
# otp_inbox.py
import os
import re
import time
import uuid
import requests
API = "https://api.testmail.app/api/json"
NAMESPACE = os.environ["TESTMAIL_NAMESPACE"]
APIKEY = os.environ["TESTMAIL_APIKEY"]
def new_inbox(prefix="otp"):
tag = f"{prefix}.{uuid.uuid4().hex[:8]}"
return {"tag": tag, "address": f"{NAMESPACE}.{tag}@inbox.testmail.app", "since": int(time.time() * 1000)}
def next_email(inbox, timeout=90):
"""Waits on testmail.app's side for the next email to this inbox."""
params = {
"apikey": APIKEY,
"namespace": NAMESPACE,
"tag": inbox["tag"],
"timestamp_from": inbox["since"],
"livequery": "true",
}
deadline = time.monotonic() + timeout
while (left := deadline - time.monotonic()) > 0:
try: # requests' timeout covers one response, so the loop keeps the whole wait under `timeout`
res = requests.get(API, params=params, timeout=(10, left), allow_redirects=False)
except requests.exceptions.ReadTimeout:
break
if res.status_code == 307: # no email within the API's one-minute hold: ask again
continue
body = res.json()
if body["result"] != "success":
raise RuntimeError(f"testmail.app: {body['message']}")
email = min(body["emails"], key=lambda e: e["timestamp"]) # oldest new email
inbox["since"] = email["timestamp"] + 1
return email
raise TimeoutError(f"No email to {inbox['address']} within {timeout} s")
def otp_from(email, pattern=r"\b\d{6}\b"):
match = re.search(pattern, email["text"])
if not match:
raise AssertionError(f"No code matching {pattern} in {email['subject']!r}")
return match.group(0)Java
// OtpInbox.java
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
public final class OtpInbox {
private static final String NS = System.getenv("TESTMAIL_NAMESPACE");
private static final String KEY = System.getenv("TESTMAIL_APIKEY");
private static final Pattern CODE = Pattern.compile("\\b\\d{6}\\b");
private static final Duration WAIT = Duration.ofSeconds(90);
private static final HttpClient HTTP = HttpClient.newHttpClient(); // doesn't follow redirects; the loop below does
private OtpInbox() {}
/** Waits for the next email to {namespace}.{tag} received after sinceMillis and returns its code. */
public static String waitForCode(String tag, long sinceMillis) throws Exception {
String url = "https://api.testmail.app/api/json?apikey=" + enc(KEY) + "&namespace=" + enc(NS)
+ "&tag=" + enc(tag) + "×tamp_from=" + sinceMillis + "&livequery=true";
long deadline = System.nanoTime() + WAIT.toNanos();
while (true) {
long left = deadline - System.nanoTime();
if (left <= 0) {
throw new IllegalStateException("No email to " + NS + "." + tag + "@inbox.testmail.app within " + WAIT.toSeconds() + " s");
}
HttpRequest request = HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofNanos(left)).GET().build();
HttpResponse<String> response;
try {
response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
} catch (HttpTimeoutException e) {
continue; // the deadline passed while the API was holding the request
}
if (response.statusCode() == 307) {
continue; // no email within the API's one-minute hold: ask again
}
JSONObject body = new JSONObject(response.body());
if (!"success".equals(body.getString("result"))) {
throw new IllegalStateException("testmail.app: " + body.optString("message"));
}
JSONArray emails = body.getJSONArray("emails"); // newest first
JSONObject email = emails.getJSONObject(emails.length() - 1); // the oldest new email
Matcher match = CODE.matcher(email.getString("text"));
if (!match.find()) {
throw new IllegalStateException("No six-digit code in \"" + email.getString("subject") + "\"");
}
return match.group();
}
}
private static String enc(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
}You’ll need to add org.json to your project’s classpath. For more information about setting up Selenium in Java, refer to our guide on email testing with Selenium and Java.
A complete OTP test suite in Playwright
This suite covers the end-to-end rows of our checklist, plus single-use and expiry behaviour; tests for the API rows, which don’t involve the UI at all, are in the next section. As before, these tests make use of the Inbox class above; labels, button names, URLs and API endpoints (we’ve used /api/auth/verify) will need to be replaced with the ones used by your app.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true, // every test has its own inbox
retries: process.env.CI ? 2 : 0,
use: { baseURL: process.env.BASE_URL ?? 'http://localhost:3000' },
});// tests/otp.spec.ts
import { test, expect, type Page } from '@playwright/test';
import { Inbox, otpFrom, wrongCode } from './otp';
test.describe.configure({ timeout: 120_000 });
async function requestCode(page: Page, inbox: Inbox) {
await page.goto('/login');
await page.getByLabel('Email').fill(inbox.address);
await page.getByRole('button', { name: 'Send code' }).click();
}
async function enterCode(page: Page, code: string) {
await page.getByLabel('Code').fill(code);
await page.getByRole('button', { name: 'Verify' }).click();
}
test('a valid code signs the user in, and arrives quickly', async ({ page }) => {
const inbox = new Inbox();
await requestCode(page, inbox);
const started = Date.now();
const email = await inbox.next();
expect.soft(Date.now() - started, 'milliseconds until the code arrived').toBeLessThan(30_000);
expect(email.subject).toMatch(/code/i);
await enterCode(page, otpFrom(email));
await expect(page).toHaveURL(/\/dashboard/);
});
test('a wrong code is rejected', async ({ page }) => {
const inbox = new Inbox();
await requestCode(page, inbox);
const code = otpFrom(await inbox.next());
await enterCode(page, wrongCode(code));
await expect(page.getByRole('alert')).toContainText(/invalid|incorrect/i);
await expect(page).not.toHaveURL(/\/dashboard/);
});
test('a resend replaces the earlier code', async ({ page }) => {
const inbox = new Inbox();
await requestCode(page, inbox);
const first = otpFrom(await inbox.next());
await page.getByRole('button', { name: 'Resend code' }).click();
const second = otpFrom(await inbox.next()); // waits for the newer email
expect(second).not.toBe(first);
await enterCode(page, first);
await expect(page.getByRole('alert')).toContainText(/invalid|expired/i);
await enterCode(page, second);
await expect(page).toHaveURL(/\/dashboard/);
});
test('too many wrong codes lock the attempt', async ({ page }) => {
const inbox = new Inbox();
await requestCode(page, inbox);
const code = otpFrom(await inbox.next());
for (let attempt = 1; attempt <= 5; attempt++) {
await enterCode(page, wrongCode(code));
}
await expect(page.getByRole('alert')).toContainText(/too many attempts/i);
await enterCode(page, code); // even the right code no longer works
await expect(page).not.toHaveURL(/\/dashboard/);
});
test('a code works only once', async ({ page, request }) => {
const inbox = new Inbox();
await requestCode(page, inbox);
const code = otpFrom(await inbox.next());
const first = await request.post('/api/auth/verify', { data: { email: inbox.address, code } });
expect(first.ok()).toBe(true);
const again = await request.post('/api/auth/verify', { data: { email: inbox.address, code } });
expect(again.status()).toBe(400);
});
test('an expired code is rejected', async ({ page }) => {
const ttl = Number(process.env.OTP_TTL_SECONDS);
test.skip(!ttl || ttl > 30, 'needs a short OTP lifetime, such as OTP_TTL_SECONDS=5, in this environment');
const inbox = new Inbox();
await requestCode(page, inbox);
const code = otpFrom(await inbox.next());
await page.waitForTimeout((ttl + 1) * 1000); // the server decides expiry, so real time has to pass
await enterCode(page, code);
await expect(page.getByRole('alert')).toContainText(/expired/i);
});Some notes on the above tests:
- The resend test is probably the most valuable one in the lot. Note that it relies on
next()waiting for a new email, and will pick up the mistake of sending a new code on resend but still accepting the old one. - The single-use test makes use of the API directly, as the only way to enter a second code in many UIs is to request a new one, which would invalidate the first.
- For expiry, configure your test environment so that codes only last a few seconds. Faking the passage of time using Playwright’s
page.clockwon’t help here, as it only affects time within the browser whereas code expiry is decided server-side. - We’ve made the check on email delivery time soft; this will report slow email delivery on flaky days without failing the whole test. Once you have an idea of normal delivery times you can convert this to a hard assertion.
- Configure your test environment to lock out users after the same number of failed logins as production. If lockout outlasts the test itself, make sure that each test run uses a new email address; the
Inboxclass above takes care of that.
API tests: the cooldown, one address per code, and no account enumeration
Three of the rows of our checklist have to do with API behaviour rather than anything visible in the UI, so it makes sense to skip using a browser and make requests directly, using Playwright’s request fixture. Again, these tests use the Inbox class to obtain one-time passwords from the test inbox:
// tests/otp-api.spec.ts
import { test, expect, type APIRequestContext } from '@playwright/test';
import { Inbox, otpFrom } from './otp';
// Placeholders for your app's own endpoints
const SEND_CODE = '/api/auth/otp';
const VERIFY = '/api/auth/verify';
// However your test setup already creates a user: a seed script, an admin API or a signup call
async function createAccount(request: APIRequestContext, email: string) {
expect((await request.post('/api/test/users', { data: { email } })).ok()).toBe(true);
}
test.describe.configure({ timeout: 120_000 });
test('a second code request during the cooldown is refused', async ({ request }) => {
const inbox = new Inbox();
expect((await request.post(SEND_CODE, { data: { email: inbox.address } })).ok()).toBe(true);
await inbox.next(); // the first code arrived
const again = await request.post(SEND_CODE, { data: { email: inbox.address } });
expect(again.status()).toBe(429);
});
test('a code works only for the address it was sent to', async ({ request }) => {
const alice = new Inbox();
const bob = new Inbox();
await request.post(SEND_CODE, { data: { email: alice.address } });
await request.post(SEND_CODE, { data: { email: bob.address } });
const aliceCode = otpFrom(await alice.next());
const bobCode = otpFrom(await bob.next()); // Bob has a live code of his own
test.skip(aliceCode === bobCode, 'the two codes matched by chance');
const swapped = await request.post(VERIFY, { data: { email: bob.address, code: aliceCode } });
expect(swapped.ok()).toBe(false);
// Control: the same code still works for the address it was sent to
const own = await request.post(VERIFY, { data: { email: alice.address, code: aliceCode } });
expect(own.ok()).toBe(true);
});
test('an address with no account gets the same answer as one with an account', async ({ request }) => {
const member = new Inbox();
await createAccount(request, member.address);
const stranger = new Inbox(); // never signed up
const forMember = await request.post(SEND_CODE, { data: { email: member.address } });
const forStranger = await request.post(SEND_CODE, { data: { email: stranger.address } });
expect(forMember.ok()).toBe(true);
expect(forStranger.status()).toBe(forMember.status());
expect(await forStranger.text()).toBe(await forMember.text());
});- Note the control requests we’ve included in each test: in the address test, to prove that it’s the email address and not a universally-failing verification endpoint that’s causing the OTP to be rejected (the final request shows that the OTP itself would have been accepted); in the enumeration test,
forMember.ok()stops two identical errors from passing as “the same answer”. - Compare what your endpoint actually returns. If the body carries a request ID or a timestamp, compare its message field instead. Response time is one of the ways to enumerate accounts warned about in the OWASP Authentication Cheat Sheet. For example, if you send the email before responding to known accounts, do it in a background job so that both responses take the same time.
- The cooldown test retries as soon as it gets the first email, so any cooldown will work as long as it’s longer than the email delivery time. Usually you’ll get 429, but you can adapt the assertion if your API behaves differently.

The two-user test · a code works only for the address it was sent to

Leaky vs safe replies to a code request · account enumeration
Cypress and other frameworks
In Cypress, the same test uses the newInbox, waitForEmail and codeFrom commands described in the Cypress email testing guide, with cy.task() keeping the API key in the Node process running Cypress:
// cypress/e2e/otp.cy.js
it('an email OTP signs the user in', () => {
cy.newInbox('otp').then((inbox) => {
cy.visit('/login');
cy.get('input[name=email]').type(inbox.address);
cy.contains('button', 'Send code').click();
cy.waitForEmail(inbox)
.then((email) => cy.codeFrom(email))
.then((code) => cy.get('input[name=code]').type(code));
cy.contains('button', 'Verify').click();
cy.location('pathname').should('eq', '/dashboard');
});
});If your existing OTP tests use Cypress.env() to get the key, they will fail on Cypress 16, which no longer supports it. The guide has instructions for both replacements.
The pattern is the same in every framework: make an address, trigger the code, wait for the email through the API, extract the code, submit it. Examples of end-to-end OTP tests with other frameworks:
- Playwright: signup, OTP and password reset
- Selenium with Java and password reset testing with Selenium
- TestCafe and Nightwatch.js
Running OTP tests in CI
Add the testmail.app API key as a GitHub Actions secret and the namespace as a variable:
- name: Run OTP tests
run: npx playwright test tests/otp.spec.ts
env:
BASE_URL: https://staging.yourapp.com
TESTMAIL_APIKEY: ${{ secrets.TESTMAIL_APIKEY }}
TESTMAIL_NAMESPACE: ${{ vars.TESTMAIL_NAMESPACE }}
OTP_TTL_SECONDS: 5 # must match the OTP lifetime the staging app is configured withThen set up the environment the tests run against:
- Configure your app to use a real email provider in CI (or staging). Configure it to only allow emails to be sent to
inbox.testmail.appemail addresses. Be aware of any sandbox restrictions; for example, Amazon SES in sandbox mode will only send to verified recipients. - Use a short expiry (a few seconds) for the OTP so that testing expiry takes seconds, not minutes. Or point the expiry test at a different instance of your app with a short expiry.
- Relax any rate limits that are per IP address for test traffic, as CI providers will run tests from the same IP addresses, but leave the per-email-address cooldown to request another code in place, as the cooldown test tests that and your tests will use a different email address anyway.
- Retries and parallel test runs don’t need any special handling, as each test creates a new
Inboxemail address, including on a retry. - API usage: the API’s
next()method makes a new API request each time it’s called as well as a re-issued request for each minute it waits, so you may run into the free plan’s rate limits above about 1,000 requests per hour if you’re running lots of tests in parallel. Large parallel suites belong on a paid plan.
Notes for Supabase and Clerk
Supabase. signInWithOtp() sends a magic link by default. To send a six-digit code, put {{ .Token }} in the Magic Link email template, then verify it with supabase.auth.verifyOtp({ email, token, type: 'email' }). By default a user can request a code once every 60 seconds and it expires after an hour; the Email OTP expiration setting changes that, and it also governs magic links and other email links. For tests:
- On hosted projects, set up custom SMTP. Supabase’s built-in email service is heavily rate-limited and can only send emails to members of your team, so test addresses won’t receive anything.
- Use a shorter OTP expiration setting on your staging project to speed up OTP expiration tests.
- The test for requesting a new code should have a longer timeout to account for the 60 seconds between OTP requests.
- When running Supabase locally with the CLI, emails are sent to Mailpit included with the CLI at
localhost:54324, which is fine for local runs. Use a test inbox when running against a staging environment or in CI.
Clerk. For development instances, Clerk provides a testing mode which is enabled by default. Any email address with +clerk_test (like jane+clerk_test@example.com) will use 424242 as the OTP code and Clerk will not send an email to that address. While this will make your UI tests fast and reliable, it will also mean you aren’t testing that Clerk actually sent an email. To test that behavior, sign up using an actual inbox (like one from testmail.app) and grab the code from the email like in the other examples. Clerk’s @clerk/testing package offers testing tokens which can help when testing against Clerk’s bot protection measures in E2E tests.
Firebase Authentication’s passwordless email sign-in uses a link instead of a code. Check out magic link testing to see how you can test that flow.
Troubleshooting OTP tests
| Symptom | Likely cause | Fix |
|---|---|---|
| The code email never arrives | The app sent to a different address, or the test environment can't send to outside addresses (a provider sandbox, Supabase's built-in email service) | Log the address the test used, check the provider's activity log, and configure real SMTP for the environment |
| The test types an old code | No timestamp_from, or two tests share an address | One Inbox per test, and call next() for every new email so it moves past the last one |
| "No code matching" | The format changed, the code is only in the HTML part, or it's split with a space | Update the pattern, read text, or use the label-anchored patterns above |
| The code is already expired when typed | The test environment's lifetime is shorter than delivery takes, or a fixed sleep added the delay | Wait on the server instead of sleeping, and compare the lifetime with the measured time to inbox |
| The resend test gets the first code back | next() was called on a new Inbox, so it doesn't know about the first email | Keep the same Inbox object for every email in a test |
| The request step fails with HTTP 429 | A resend cooldown or a per-IP limit on the shared CI runner | Relax per-IP limits for test traffic, and give the resend test enough time for the cooldown |
| The wrong-code test sometimes passes | A hard-coded "wrong" code such as 000000 happened to be right | Derive it from the real code, as wrongCode() does |
| Lockout tests break other tests | Tests share an account, so one test's lockout blocks the next | A new address, and so a new account, per test |
| Passes locally, flaky in CI | Slower delivery in CI, or parallel tests sharing state | A server-side wait with a generous cap, unique addresses, and a soft timing assertion |
| Cypress OTP tests break after an upgrade | Cypress 16 removed Cypress.env() | Move the API call into cy.task(), or read the key with cy.env() |
FAQ
How do you automate email OTP testing in CI/CD?
Generate a unique email address for each test. Initiate the code request in your UI or directly through the API. Use an email testing service API to wait for the email to be received, parse the OTP out of the email body with a regular expression, and complete your flow using the OTP. Make sure your application sends actual emails in your testing environment, to test addresses only, and add the email testing service API key as a secret in your CI/CD provider.
How do I extract an OTP code from an email in a test?
Parse the text content of the email (not the HTML) and use a regular expression that matches the type of code your app expects. For example, if your app expects a six-digit code, you could use /\b\d{6}\b/. If your app generates codes that include letters, anchor the pattern to the label ("code:") so it can’t match other capitalized words. Make sure your test fails with a helpful error message if it can’t find a match!
How do I wait for an OTP email without a fixed delay?
Use an API which can wait for emails on the server. The live queries (livequery=true) in testmail.app’s API block until the email arrives, which makes it possible to move on in your test right away. If you instead used a static sleep you’d waste time if the email arrived quickly, and your test could still fail if it took longer.
How do I test OTP expiry without waiting ten minutes?
Configure the validity period of OTPs in your test environment to be short, e.g. a few seconds, and wait slightly longer than that in your test. Faking time in your browser won’t help, since it’s the server which knows whether an OTP has expired.
Can I check an email OTP online?
Yes. Request an OTP to be sent to a testmail.app email address, e.g. {namespace}.check@inbox.testmail.app, and view the JSON API in a browser (add pretty=true to have it nicely formatted) to read the email and its code. On Pro and higher plans you can also view the rendered emails graphically.
What's the difference between an email testing API and a temporary email service?
Temporary email services focus on offering a public, disposable inbox in the browser for humans to check emails, while an email testing API focuses on features that are helpful for automated OTP tests, such as private email addresses, filtering, waiting for emails and accessing emails with parsed HTML and plain-text content.
Is email OTP the same as two-factor authentication?
Email OTPs are not always used as a second factor, and they can also replace passwords (“passwordless”). The tests are the same in both cases, except that for a second factor you should also test that logging in with only a password (skipping the 2FA step) does not result in a logged-in state.
Try it: sign up for a free account on testmail.app, copy the files tests/otp.ts and tests/otp.spec.ts into your project and run npx playwright test tests/otp.spec.ts.