Test the email-change confirmation flow with Playwright
Changing the email address on an account is one of the riskiest flows to get wrong. The new address must be confirmed before it replaces the old one, the old address should be told about the change, and a link that was already used or replaced must not work a second time. Each of these is an email, so each can be asserted. This guide shows a Playwright Test spec that uses two unique inboxes, one for the old address and one for the new one, and walks the whole flow. It assumes your app sends a confirmation link to the new address and, optionally, a notice to the old one.
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 magic_link, or 408 if nothing arrived. Messages are deleted after 24 hours. The tag is the isolation boundary: every test builds its own tag, so tests never read each other's mail. This flow needs two tags, one per address, which makes it a good fit: the old inbox and the new inbox are separate and can be waited on independently.
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 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.
The flow under test
The spec follows these steps. Adjust the labels and subjects to your app.
- Create an account with the old address and sign in. A small helper can do this through your app's API instead of the UI, which keeps the test short.
- Open the account settings and request a change to the new address.
- Wait for the confirmation email in the new inbox and read
magic_link. - Optionally wait for a notice in the old inbox. Many apps send one so the owner of the old address can object.
- Open the link and assert the account now shows the new address.
- Open the same link again and assert it is rejected.
The helper
Save this as tests/inbox.js. It needs Node 18 or newer for the built-in fetch. newInbox returns a tag and an address, so calling it twice gives you the two addresses.
const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
if (!KEY || !NAMESPACE) {
throw new Error("Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE");
}
let counter = 0;
function newInbox(label) {
const tag = (label + "-" + Date.now().toString(36) + "-" + ++counter + "-" + Math.random().toString(36).slice(2, 6)).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: { Authorization: "Bearer " + KEY },
});
if (res.status === 200) return res.json();
if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status + " for tag " + tag);
}
throw new Error("No matching email arrived for tag " + tag);
}
async function deleteEmails(tag) {
await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), {
method: "DELETE",
headers: { Authorization: "Bearer " + KEY },
});
}
module.exports = { newInbox, waitForEmail, deleteEmails };
The spec
Save this as tests/email-change.spec.js. The helper createAccount is a placeholder for your own set-up call; replace it and the page labels with those of your app.
const { test, expect } = require("@playwright/test");
const { newInbox, waitForEmail, deleteEmails } = require("./inbox");
const APP = process.env.APP_URL || "http://localhost:3000";
async function createAccount(request, email) {
const res = await request.post(APP + "/api/test/accounts", {
data: { email, password: "correct horse battery staple" },
});
expect(res.ok()).toBeTruthy();
}
test("changing the email needs confirmation from the new address", async ({ page, request }) => {
const oldInbox = newInbox("change-old");
const newOne = newInbox("change-new");
try {
await createAccount(request, oldInbox.email);
await page.goto(APP + "/login");
await page.getByLabel("Email").fill(oldInbox.email);
await page.getByLabel("Password").fill("correct horse battery staple");
await page.getByRole("button", { name: "Sign in" }).click();
await page.goto(APP + "/settings/email");
await page.getByLabel("New email").fill(newOne.email);
await page.getByRole("button", { name: "Change email" }).click();
await expect(page.getByText("Check your new inbox")).toBeVisible();
const confirmation = await waitForEmail(newOne.tag, { subject: "confirm" });
expect(confirmation.magic_link).toContain("/confirm-email");
const notice = await waitForEmail(oldInbox.tag, { subject: "email address" });
expect(notice.subject.toLowerCase()).toContain("changed");
await page.goto(APP + "/settings/email");
await expect(page.getByText(oldInbox.email)).toBeVisible();
await page.goto(confirmation.magic_link);
await expect(page.getByText(newOne.email)).toBeVisible();
await page.goto(confirmation.magic_link);
await expect(page.getByText(/expired|already used|invalid/i)).toBeVisible();
} finally {
await deleteEmails(oldInbox.tag);
await deleteEmails(newOne.tag);
}
});
Before the link is opened, the test checks that the settings page still shows the old address. That assertion is the one that catches an app which switches the address too early, before the new one has been proven.
Asserting that nothing was sent
Some apps must not send mail. If a user asks to change to an address that already belongs to another account, many products stay silent to avoid revealing which addresses are registered. To test that, request the change and then assert that the wait times out. Use a short timeout so the test stays quick, and only assert absence after you have asserted that a positive case works in the same run; otherwise a broken helper passes the test.
test("no mail for a taken address", async ({ page, request }) => {
const taken = newInbox("change-taken");
const target = newInbox("change-target");
try {
await createAccount(request, taken.email);
await createAccount(request, target.email);
// sign in as the first account and ask to change to the second account's address
// ... same UI steps as above, using target.email ...
const params = new URLSearchParams({ tag: target.tag, timeout: "5" });
const res = await fetch("https://assertinbox.com/v1/wait?" + params, {
headers: { Authorization: "Bearer " + process.env.ASSERTINBOX_KEY },
});
expect(res.status).toBe(408);
} finally {
await deleteEmails(taken.tag);
await deleteEmails(target.tag);
}
});
The timeout query parameter is in seconds. A 408 means no message arrived in that time, which is the result you want here.
What to check beyond the happy path
- The link is single-use. The last assertion above covers it. If your app deliberately allows reuse within a window, assert that instead.
- A second request replaces the first. Request two changes in a row, then assert that the first link is rejected and the second works. Wait for each mail by its own tag or filter on
subjectand pick the newest. - The link is bound to the session or the account. If your app requires being signed in to confirm, open the link in a fresh browser context and assert it asks for a login first.
- The old address stops working for login. After confirmation, sign in with the old address and assert it fails.
Troubleshooting
- The wait times out on the new inbox. The app may send to a normalised or lower-cased address. The helper lower-cases the tag, so compare in your app's log what address it used.
- The notice arrives but the confirmation does not. Check that the app sends the confirmation to the new address and not to the account's current one.
- The link opens on a different host. Staging mail often contains production links. Set the app's base URL for the test environment.
- HTTP 429. You reached the daily allowance of 2,000 requests per key. The
Retry-Afterheader gives the seconds until 00:00 UTC.
Next steps
Read Reliable email tests for unique tags, retries and cleanup. Related guides: Playwright email verification, testing password reset emails and email 2FA login codes. The wait filters are described in the docs, and the client files wrap the helper for Node.js and Python.
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.