Guide · Testing
Receive OTP emails in Playwright tests without flaky sleeps
End-to-end tests for sign-up, magic-link login and password reset all hit the same wall: the app sends an email, and the test has to read it. The usual workaround, await page.waitForTimeout(10000) and then a look in a mailbox, is slow on good days and red on bad ones.
This guide replaces the sleep with a long-poll against a real inbox. The test marks the inbox, triggers the email, and makes one request that returns the moment the message lands, with the one-time code already extracted. Examples in TypeScript (Playwright Test) and Python (pytest-playwright).
Last reviewed:
Why sleeps and polling loops make tests flaky
Email delivery time varies from run to run, and a provider that queues can make it much longer. A fixed sleep has to be set for the slow case and then wastes that time on every run. A hand-written polling loop is better, but it is more code, spends a request every second or two, and has its own classic bug: it finds the code from the previous run, which is still in the inbox, and passes against the wrong email.
Two API parameters remove both problems:
since: only messages received strictly after a point, given as a message id or an ISO timestamp. Take the newest id before triggering the email and old mail can never match.wait: hold the request for up to 25 seconds until a matching message arrives. On timeout it answers200with an empty list, so the test asks again until its own deadline.
The message detail then carries extracted.codes (likely one-time codes, best first) and extracted.links (verification-looking links first, with Gmail, Outlook Safe Links and Proofpoint redirects unwrapped). Extraction is a heuristic, so the full text and HTML are there when you need to assert on them yourself.
Set up an inbox and a key for CI
- Create an inbox such as
ci-signup@agent.restapi.emailin the dashboard. - Create an
sk_live_API key limited to that inbox. - Store it as a CI secret named
RESTAPI_EMAIL_KEY. Never commit it.
# .github/workflows/e2e.yml (excerpt)
- name: Run Playwright tests
run: npx playwright test
env:
RESTAPI_EMAIL_KEY: ${{ secrets.RESTAPI_EMAIL_KEY }}The inbox is receive-only and keeps messages for 30 days, which is plenty for debugging a failed run from last week. Your app under test sends the email with whatever provider it already uses.
Playwright Test (TypeScript)
Two helpers, built on Playwright’s own request fixture so they share its tracing and reporting. markInbox returns the newest message id (or the epoch, when the inbox is empty); waitForEmail long-polls until a newer message arrives and then fetches it in full.
// tests/inbox.ts
import { expect, type APIRequestContext } from '@playwright/test';
const API = 'https://api.restapi.email';
const headers = { 'X-API-Key': process.env.RESTAPI_EMAIL_KEY ?? '' };
/** Call before the action that sends the email. */
export async function markInbox(request: APIRequestContext, inbox: string) {
const res = await request.get(`${API}/api/v1/emails/${inbox}/messages`, {
headers, params: { limit: 1 },
});
expect(res.ok()).toBeTruthy();
const { emails } = await res.json();
return emails[0]?.id ?? '1970-01-01T00:00:00Z';
}
/** Long-poll until a newer email arrives, then return it in full. */
export async function waitForEmail(
request: APIRequestContext, inbox: string, since: string,
{ timeoutMs = 90_000, q }: { timeoutMs?: number; q?: string } = {},
) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const wait = Math.max(1, Math.min(25, Math.floor((deadline - Date.now()) / 1000)));
const params: Record<string, string | number> = { since, wait };
if (q) params.q = q;
const res = await request.get(`${API}/api/v1/emails/${inbox}/messages`, {
headers, params, timeout: (wait + 10) * 1000,
});
expect(res.ok()).toBeTruthy();
const { emails } = await res.json();
if (emails.length === 0) continue; // timed out: ask again
const detail = await request.get(
`${API}/api/v1/emails/${inbox}/messages/${emails[0].id}`, { headers },
);
expect(detail.ok()).toBeTruthy();
return (await detail.json()).email;
}
throw new Error(`No email for ${inbox} within ${timeoutMs} ms`);
}// tests/signup.spec.ts
import { test, expect } from '@playwright/test';
import { markInbox, waitForEmail } from './inbox';
const INBOX = 'ci-signup@agent.restapi.email';
test('new user confirms their email with the OTP', async ({ page, request }) => {
test.setTimeout(120_000); // the default 30 s is shorter than one slow email
const since = await markInbox(request, INBOX);
const name = `ci-${Date.now()}`; // unique text the email will contain
await page.goto('/signup');
await page.getByLabel('Name').fill(name);
await page.getByLabel('Email').fill(INBOX);
await page.getByRole('button', { name: 'Create account' }).click();
const email = await waitForEmail(request, INBOX, since, { q: name });
expect(email.subject).toContain('Confirm');
const code = email.extracted.codes[0];
expect(code, 'no code found in: ' + email.text_content).toBeTruthy();
await page.getByLabel('Verification code').fill(code);
await page.getByRole('button', { name: 'Verify' }).click();
await expect(page.getByText('Welcome')).toBeVisible();
});Details that matter
- Playwright’s default test timeout is 30 seconds, shorter than one slow email plus the UI work. Raise it with
test.setTimeoutfor email tests. - The request timeout is set above the
wait, so the client never gives up before the server answers. - The list returns summaries only (
id,from,to,subject,received_at). The body andextractedcome from the second request,GET …/messages/{id}. - When the assertion on the code fails, the message prints
text_content, so the CI log shows what the email actually said.
pytest-playwright (Python)
The same flow with requests. Because the API is plain HTTPS with one header, the helpers work unchanged in Selenium, Cypress tasks or a plain integration test.
# tests/test_signup.py (pip install pytest-playwright requests)
import os, time, requests
from playwright.sync_api import Page, expect
API = "https://api.restapi.email"
INBOX = "ci-signup@agent.restapi.email"
HEADERS = {"X-API-Key": os.environ["RESTAPI_EMAIL_KEY"]}
def mark_inbox(inbox: str) -> str:
r = requests.get(f"{API}/api/v1/emails/{inbox}/messages",
params={"limit": 1}, headers=HEADERS, timeout=15)
r.raise_for_status()
emails = r.json()["emails"]
return emails[0]["id"] if emails else "1970-01-01T00:00:00Z"
def wait_for_email(inbox: str, since: str, timeout: float = 90, q: str | None = None) -> dict:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
wait = max(1, min(25, int(deadline - time.monotonic())))
params = {"since": since, "wait": wait, **({"q": q} if q else {})}
r = requests.get(f"{API}/api/v1/emails/{inbox}/messages",
params=params, headers=HEADERS, timeout=wait + 10)
r.raise_for_status()
emails = r.json()["emails"]
if not emails:
continue # timed out: ask again
d = requests.get(f"{API}/api/v1/emails/{inbox}/messages/{emails[0]['id']}",
headers=HEADERS, timeout=15)
d.raise_for_status()
return d.json()["email"]
raise TimeoutError(f"No email for {inbox} within {timeout} s")
def test_signup_otp(page: Page):
since = mark_inbox(INBOX)
name = f"ci-{int(time.time() * 1000)}"
page.goto("https://staging.example.com/signup")
page.get_by_label("Name").fill(name)
page.get_by_label("Email").fill(INBOX)
page.get_by_role("button", name="Create account").click()
email = wait_for_email(INBOX, since, q=name)
codes = email["extracted"]["codes"]
assert codes, email["text_content"]
page.get_by_label("Verification code").fill(codes[0])
page.get_by_role("button", name="Verify").click()
expect(page.get_by_text("Welcome")).to_be_visible()Parallel workers and shared inboxes
Playwright runs tests in parallel by default. If two tests sign up with the same inbox at the same moment, each might read the other’s email. There are three clean ways out:
- Filter by content. Put a unique value into the form (a name, a company, an order number) and pass it as
q, a full-text search over subject and body. The wait keeps going until a message matching bothsinceandqarrives. The examples above do this. - One inbox per worker. Derive the address from
testInfo.parallelIndex. Inboxes count against your plan, so this suits larger plans. - Run email tests serially.
test.describe.configure({ mode: 'serial' })for the email suite only.
Addresses are matched exactly: mail to a plus-address such as ci+run42@… is rejected as an unknown recipient, so use q instead. Each key may start up to 30 long polls a minute and about 120 requests a minute in total, which is plenty for a typical suite. A very wide matrix should use more than one key.
Magic links and password resets
For a magic link, read email.extracted.links[0] and page.goto() it. Links that a corporate mail filter would wrap (Outlook Safe Links, Proofpoint) or that arrive through Gmail redirects are unwrapped to their destination, and unsubscribe and tracking-pixel links are left out, so the first link is usually the one you want. Assert on its host before visiting it, so a test never follows an unexpected URL.
To test the email itself rather than the flow, assert on subject, from, text_content and html_content, or on the headers object. File attachments are discarded before storage, so this is not a tool for testing attachments.
Questions
Why not just sleep for ten seconds and then read the inbox?
A fixed sleep is either too short on a slow day, which fails the test, or too long on every other day, which slows the suite. A long-poll with wait=25 returns as soon as the email lands and only waits longer when it has to.
Can parallel Playwright workers share one inbox?
Yes if each test can tell its email apart: pass since and a q search term that only its email contains, such as a unique name typed into the form. Otherwise give each worker its own inbox or run the email tests serially.
How long can one request wait?
Up to 25 seconds (wait=25). On timeout the API answers 200 with an empty list, so loop until your own deadline. Set the HTTP client timeout above the wait, and note each key may start up to 30 long polls a minute.
Does this work with the Python version of Playwright?
Yes. The API is plain HTTPS with an X-API-Key header, so any HTTP client works: the guide shows Playwright Test in TypeScript and pytest-playwright with requests.