Test email 2FA and login codes with Playwright
Many apps send a short code by email as a second step after the password: the user logs in, receives a six-digit code, and types it to finish. This guide tests that flow end to end in Playwright Test (plain JavaScript). The test logs in with a password, waits for the code email with the subject and after filters, enters the otp and asserts the signed-in state. It also covers the three cases that break most often: a wrong code, a resent code where only the newest should work, and an expired code.
What your app needs
A login page with an email and password, followed by a code page that sends the code by email. The test uses a test-only endpoint, POST /test-support/users, to create a user with a known address and password. That endpoint is an assumption: replace it with your seeding method, such as a database fixture or a command run before the suite, and never expose it in production. The labels, button names and messages in the test are placeholders; replace them with those of your app.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, including id, subject, otp and links. Messages are deleted after 24 hours. The otp field holds the code found in the message.
Get an API key
Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so store it in your CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export both values for the tests: ASSERTINBOX_KEY is the api_key and ASSERTINBOX_NAMESPACE is the namespace. If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are listed in the limits page.
The helper
Save this as tests/inbox.js. It needs Node 18 or newer for the built-in fetch. waitForEmail accepts the filters and retries on a 408 timeout, and latestId returns the id of the newest message for a tag, or undefined when there is none.
const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
function headers() {
return { Authorization: "Bearer " + KEY };
}
function newInbox(prefix) {
const random = Math.random().toString(36).slice(2, 8);
const tag = (prefix + "-" + Date.now() + "-" + random).toLowerCase();
return { tag, email: NAMESPACE + "." + tag + "@assertinbox.com" };
}
async function waitForEmail(tag, filters) {
const params = new URLSearchParams({ tag, timeout: "25", ...filters });
for (let attempt = 0; attempt < 3; attempt++) {
const res = await fetch(API + "/v1/wait?" + params, { headers: headers() });
if (res.status === 200) return res.json();
if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status);
}
throw new Error("No matching email arrived for tag " + tag);
}
async function latestId(tag) {
const res = await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { headers: headers() });
if (!res.ok) throw new Error("AssertInbox returned HTTP " + res.status);
const body = await res.json();
return body.messages.length ? body.messages[0].id : undefined;
}
async function deleteEmails(tag) {
await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { method: "DELETE", headers: headers() });
}
module.exports = { newInbox, waitForEmail, latestId, deleteEmails };
The tests
Save this as tests/email-2fa.spec.js. Each test gets its own user and its own tag, so the tests can run in parallel. Within one test the tag stays the same for the user, and after separates the first email from the second.
const { test, expect } = require("@playwright/test");
const { newInbox, waitForEmail, latestId, deleteEmails } = require("./inbox");
const APP = process.env.APP_URL || "http://localhost:3000";
const PASSWORD = "correct-horse-battery-9";
test.describe("email login code (2FA)", () => {
test.setTimeout(120000);
let inbox;
test.beforeEach(async ({ request }) => {
inbox = newInbox("twofa");
// Test-only endpoint of your app that creates a user with this address.
await request.post(APP + "/test-support/users", { data: { email: inbox.email, password: PASSWORD } });
});
test.afterEach(async () => {
await deleteEmails(inbox.tag);
});
async function logIn(page) {
await page.goto(APP + "/login");
await page.getByLabel("Email").fill(inbox.email);
await page.getByLabel("Password").fill(PASSWORD);
await page.getByRole("button", { name: "Log in" }).click();
}
async function nextCode(after) {
const mail = await waitForEmail(inbox.tag, { subject: "login code", ...(after ? { after } : {}) });
expect(mail.otp).toMatch(/^\d{6}$/);
return mail;
}
async function submitCode(page, code) {
await page.getByLabel("Login code").fill(code);
await page.getByRole("button", { name: "Verify" }).click();
}
test("the emailed code completes the login", async ({ page }) => {
await logIn(page);
const mail = await nextCode();
await submitCode(page, mail.otp);
await expect(page.getByText("Signed in")).toBeVisible();
});
test("a wrong code is rejected", async ({ page }) => {
await logIn(page);
const mail = await nextCode();
const wrong = mail.otp === "000000" ? "111111" : "000000";
await submitCode(page, wrong);
await expect(page.getByText(/invalid|incorrect/i)).toBeVisible();
await expect(page.getByText("Signed in")).toHaveCount(0);
});
test("after a resend only the newest code works", async ({ page }) => {
await logIn(page);
const first = await nextCode();
await page.getByRole("button", { name: "Resend code" }).click();
const second = await nextCode(first.id);
expect(second.id).not.toBe(first.id);
if (second.otp !== first.otp) {
await submitCode(page, first.otp);
await expect(page.getByText(/invalid|expired/i)).toBeVisible();
}
await submitCode(page, second.otp);
await expect(page.getByText("Signed in")).toBeVisible();
});
test("an expired code is rejected", async ({ page }) => {
// Needs a test environment where codes live for a few seconds, for example
// LOGIN_CODE_TTL_SECONDS=5 in the app's test configuration.
await logIn(page);
const mail = await nextCode();
await page.waitForTimeout(7000);
await submitCode(page, mail.otp);
await expect(page.getByText(/expired/i)).toBeVisible();
});
});
Why after matters here
A resend sends a second message to the same address. Without after, the wait for the new code can return the first email again, and the test then types the old code and fails or, worse, passes for the wrong reason. The helper nextCode takes the id of the previous message and returns only a newer one. The first wait needs no after, because the user was created for this test and has not received anything yet.
The resent code
The resend test asserts the rule that most apps want: once a new code is issued, the old one stops working. The old code is typed only when it differs from the new one, because with six digits the two can be equal, rarely but not never. If your app deliberately keeps older codes valid for a short time, change the assertion to match your rule; the test documents the rule either way.
The expired code
Waiting ten minutes in a test is not practical. Give your test environment a short code lifetime, a few seconds, through a setting or environment variable of your own, then wait longer than that before typing the code. The example waits seven seconds for a lifetime of five. Do not shorten the lifetime in production. If you cannot change the lifetime, test expiry at a lower level, with a unit test that controls the clock.
Troubleshooting
- The wait times out. The app did not send the code, or sent it with a different subject. Print
inbox.emailand check your mail logs; change the subject filter to a word from the real subject. otpis null. The code is formatted in a way the extractor does not recognise. Printmail.text, and try the free extractor tool on it.- The resend test fails on the second wait. The app may rate-limit resends. Check for a cooldown and make the test environment's cooldown short.
- Tests interfere in parallel. Make sure every test creates its own user with its own address, as
beforeEachdoes. - HTTP 429 from AssertInbox. The key used its 2,000 requests for the day.
Retry-Aftergives the seconds until 00:00 UTC.
Next steps
Read Reliable email tests for unique tags, retries and cleanup. Related guides: Playwright email verification, Supabase Auth email tests and password reset tests. The wait filters are described in the docs.
Free beta, run by AI agents
This service is in free beta and is operated by AI agents under human supervision. Messages are deleted after 24 hours.