Test OTP resend and expiry in Playwright
Resend and expiry are where one-time-code flows break. A user asks for a second code and the first one still works, or a code that should have expired is accepted, or the resend button silently does nothing because of a cooldown. This guide tests those behaviours in Playwright Test: request a code, request a new one, wait for the second email, assert that the old code is rejected and the new one works, and then cover expiry without sleeping for fifteen minutes. The first example runs unchanged against the practice app on this site; the patterns after it are for your own application. It targets recent versions of @playwright/test and Node 18 or newer.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls and returns the newest matching message as JSON, including id, subject, otp and magic_link, or 408 if nothing arrived. Messages are deleted after 24 hours. Resend tests depend on one more feature: the after filter. When two emails arrive at the same address, wait({ after: first.id }) returns only messages newer than the first one, so the second wait cannot hand back the email you already have.
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 keep it in your secret manager or CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (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 on the limits page.
Set up the fixture
Download assertinbox.mjs and playwright-fixture.mjs from the client files page into your tests folder. The fixture adds an inbox object to every test. Its tag is unique for each test, worker and retry, it waits with the 408 retry already built in, and it deletes the test's messages when the test ends.
curl -O https://assertinbox.com/sdk/assertinbox.mjs
curl -O https://assertinbox.com/sdk/playwright-fixture.mjs
npm install --save-dev @playwright/test
Test a resend against the practice app
The practice app is a small fake product with a sign-up form, a verification page and a Send a new code button. Its rules are fixed so tests can rely on them: the code works once, a new code makes the old code and the old link stop working, and a new code can be requested once every 30 seconds. Save this as resend.spec.mjs and run npx playwright test resend.spec.mjs.
import { test, expect } from "./playwright-fixture.mjs";
const APP = process.env.APP_URL || "https://assertinbox.com";
async function signUp(page, email) {
await page.goto(APP + "/practice/signup");
await page.getByLabel("Email address").fill(email);
await page.getByRole("button", { name: "Create account" }).click();
await expect(page).toHaveURL(/\/practice\/verify/);
}
async function enterCode(page, code) {
await page.getByLabel("Verification code").fill(code);
await page.getByRole("button", { name: "Verify", exact: true }).click();
}
test("a resent code replaces the first one", async ({ page, inbox }) => {
test.setTimeout(120_000);
await signUp(page, inbox.address("resend"));
const first = await inbox.wait();
// The app allows one new code every 30 seconds. Click until it confirms
// instead of sleeping for a guessed time.
await expect(async () => {
await page.getByRole("button", { name: "Send a new code" }).click();
await expect(page.getByRole("status")).toContainText("A new code was sent", { timeout: 3000 });
}).toPass({ timeout: 60_000, intervals: [5000] });
const second = await inbox.wait({ after: first.id });
expect(second.otp).toMatch(/^[0-9]{6}$/);
await enterCode(page, first.otp);
await expect(page.getByRole("status")).toContainText("not valid");
await enterCode(page, second.otp);
await expect(page.getByRole("status")).toContainText("Your email is verified");
});
Three details make this test dependable. The first email is read before the resend, and its id becomes the after value for the second wait. The cooldown is handled by retrying the click until the page shows success, not by a fixed delay: toPass repeats the whole block until it stops throwing, and a rejected click shows an error message instead of the success text. And the old code is checked first, so the test proves the old code is dead before it proves the new one lives. If your app has no cooldown, delete the toPass wrapper and keep the click and the assertion.
Test a resend against your own app
The same shape fits any app. Replace the sign-up steps, the button name and the messages with yours. If your app lets one user have several valid codes at once, say so in the test name and assert that instead: wait for the second email, enter the first code and expect success. What matters is that the test records the behaviour your product promises. Two cautions apply when the resend goes through your own mail provider: the second email can arrive later than the first, so keep the wait generous, and some providers deduplicate identical messages sent close together, so a second email with the same code is a finding worth reporting, not a test to loosen.
Test expiry without waiting fifteen minutes
A test that sleeps for the real lifetime of a code is too slow to keep. There are two honest ways to test expiry, and both need a small hook in your app that exists only in test environments. The practice app has no such hook, because its fifteen-minute lifetime is fixed, so this part targets your application.
- A test clock. The app reads time from one function, and a test-only endpoint moves it forward. The test requests a code, advances the clock past the lifetime, and enters the code.
- A short expiry in the test environment. The lifetime comes from a setting such as
OTP_TTL_SECONDS, and the test environment sets it to a few seconds. The test requests a code, waits slightly longer than the setting, and enters the code. A short deliberate wait is the point of this test, so it is the one place where a fixed delay is right.
Playwright's own clock changes time in the browser only. It does not move the clock of your server, so it cannot expire a code that the server checks. Never add a time-travel endpoint to production code paths; guard it with an environment check and keep it out of production builds. Save this as expiry.spec.mjs. Both tests skip themselves when their environment variable is missing, so the file is safe to keep in the suite.
import { test, expect } from "./playwright-fixture.mjs";
const APP = process.env.APP_URL || "http://localhost:3000";
async function requestCode(page, inbox) {
await page.goto(APP + "/signup");
await page.getByLabel("Email").fill(inbox.address("expiry"));
await page.getByRole("button", { name: "Sign up" }).click();
return inbox.wait();
}
async function submit(page, code) {
await page.getByLabel("Code").fill(code);
await page.getByRole("button", { name: "Verify" }).click();
}
test("a code is rejected after the app clock passes its lifetime", async ({ page, request, inbox }) => {
test.skip(!process.env.TEST_CLOCK_URL, "needs an app with a test-only clock endpoint");
const mail = await requestCode(page, inbox);
const res = await request.post(process.env.TEST_CLOCK_URL, { data: { advanceSeconds: 901 } });
expect(res.ok()).toBeTruthy();
await submit(page, mail.otp);
await expect(page.getByRole("alert")).toContainText(/expired/i);
});
test("a code is rejected after a short test-only lifetime", async ({ page, inbox }) => {
const ttl = Number(process.env.OTP_TTL_SECONDS);
test.skip(!ttl, "needs the app to run with a short OTP_TTL_SECONDS");
const mail = await requestCode(page, inbox);
await page.waitForTimeout((ttl + 1) * 1000);
await submit(page, mail.otp);
await expect(page.getByRole("alert")).toContainText(/expired/i);
});
Keep the expiry message assertion loose, as in /expired/i, so a copy edit does not break the suite, but do assert it: a code that is rejected for the wrong reason, such as a server error, would otherwise pass as "rejected".
Run it in CI
Store ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE as secrets in your CI provider and pass them as environment variables to the step that runs npx playwright test. Never print the key. Set OTP_TTL_SECONDS and TEST_CLOCK_URL only for the staging or local app that supports them. The resend test takes about 30 seconds against the practice app because of its cooldown, so run it in its own project or tag it, and keep the quick sign-up tests in the default run.
Troubleshooting
- The second wait returns the first email. The
afteroption is missing, or it carries the wrong id. Passfirst.id. - The click never shows success. The cooldown is longer than the
toPasstimeout. Raise it, or ask for a shorter cooldown in the test environment. - The test times out at 30 seconds. Set
test.setTimeoutabove the cooldown plus the waits, as the example does. - HTTP 429 from the practice API. Each network address can make 20 sign-ups and resends an hour. Wait for the hour to pass or run fewer repetitions.
- HTTP 401. The key is missing or wrong in the environment that runs the tests.
Related guides: email login codes in Playwright, the password reset flow.
Next steps
For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.