Test a newsletter double opt-in confirmation with Playwright
A newsletter sign-up form with double opt-in has two states that matter. After the visitor submits the form, the subscriber exists but is pending and must not receive newsletters. Only after they open the link in the confirmation email do they become confirmed. Both halves break in practice: the confirmation email is not sent, the link carries a token that has expired, or a subscriber is marked confirmed without ever clicking. This guide tests both outcomes with Playwright Test and a real inbox from AssertInbox: one case where the link is opened, and one where it never is.
The guide describes how to test your own product's behaviour. It makes no statement about what consent law requires where you or your subscribers live; check the rules that apply to you.
Get an API key
Get one in a click at /start. One request creates a key and your private namespace, with no email address or card. The key is shown once, so keep it in your secret store and export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page, and the client files can replace the helper functions below.
The helper file
Save this as inbox.js next to your tests. It gives each test its own address and a wait that retries after a 408 timeout. It also reads the subscriber state from your own staging API, which you must adapt: the example assumes GET /api/subscribers?email= returns {"status": "pending"} or {"status": "confirmed"}.
const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
const APP = process.env.APP_URL || "http://localhost:3000";
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 },
});
}
async function subscriberStatus(email) {
const res = await fetch(APP + "/api/subscribers?email=" + encodeURIComponent(email));
if (res.status === 404) return "unknown";
if (!res.ok) throw new Error("subscribers API returned " + res.status);
return (await res.json()).status;
}
module.exports = { newInbox, waitForEmail, deleteEmails, subscriberStatus };
The test file
Save this as double-opt-in.spec.js. The form labels, the success message and the confirmation page text are placeholders for your own pages. Run it only against an app you own.
const { test, expect } = require("@playwright/test");
const { newInbox, waitForEmail, deleteEmails, subscriberStatus } = require("./inbox");
const APP = process.env.APP_URL || "http://localhost:3000";
async function subscribe(page, email) {
await page.goto(APP + "/newsletter");
await page.getByLabel("Email").fill(email);
await page.getByRole("button", { name: "Subscribe" }).click();
await expect(page.getByText("Check your inbox")).toBeVisible();
}
test("a subscriber is pending until the confirmation link is opened", async ({ page }) => {
const inbox = newInbox("optin");
try {
await subscribe(page, inbox.email);
expect(await subscriberStatus(inbox.email)).toBe("pending");
const mail = await waitForEmail(inbox.tag, { subject: "confirm" });
expect(mail.magic_link, "no confirmation link").toBeTruthy();
expect(new URL(mail.magic_link).host).toBe(new URL(APP).host);
await page.goto(mail.magic_link);
await expect(page.getByText("Subscription confirmed")).toBeVisible();
expect(await subscriberStatus(inbox.email)).toBe("confirmed");
} finally {
await deleteEmails(inbox.tag);
}
});
test("a subscriber who never clicks the link stays pending", async ({ page }) => {
const inbox = newInbox("optin-idle");
try {
await subscribe(page, inbox.email);
await waitForEmail(inbox.tag, { subject: "confirm" });
await page.waitForTimeout(3000);
expect(await subscriberStatus(inbox.email)).toBe("pending");
} finally {
await deleteEmails(inbox.tag);
}
});
Run it with the key in the environment:
export ASSERTINBOX_KEY=ai_your_key_here
export ASSERTINBOX_NAMESPACE=your_namespace
APP_URL=https://staging.example.com npx playwright test double-opt-in.spec.js
Why the second test matters
The first test shows the happy path. The second protects the promise behind double opt-in: nobody is subscribed on the strength of a form submission alone. A common bug is to mark the subscriber confirmed when the form is submitted, or when a mail scanner fetches the link. The test waits for the email to prove that the confirmation was sent, pauses briefly, and checks that the state did not change. A short pause is evidence, not proof; if your confirmation happens in a background job, read asserting that an email was sent once or not at all for how to choose the waiting time.
Other cases worth adding
- Resubmitting the form. Submit the same address twice and assert that the state is still pending. Use the
afterfilter with the first message'sidif your app sends a second confirmation, so the wait does not return the first email again. - An expired link. If your app expires tokens, create the subscription through a staging endpoint that back-dates it, open the link and assert the expired-link message, as in the email-change guide.
- A reused link. Open the confirmation link a second time and assert a friendly message rather than an error page.
- Unsubscribe. Once confirmed, the newsletter itself should carry an unsubscribe header; see testing the List-Unsubscribe header.
Parallel runs and cleanup
Each test calls newInbox, so Playwright's parallel workers use different tags and never see each other's mail. The finally block deletes the tag's messages even when an assertion fails. Messages are deleted after 24 hours in any case. If the confirmation link opens in a different browser context in real life (a phone, say), open it from a fresh context in the test to match; the link should not depend on the form's session.
Troubleshooting
- The wait times out. Look at what the page showed after the form was submitted; an error banner means nothing was sent. Also check the
subjectfilter, a case-insensitive substring of the real subject. magic_linkis null. The extractor looks for words such as confirm and verify in the URL or link text. Usemail.linksand pick the link with your own rule.- The status stays pending after the link. The link may require a POST button on the confirmation page to avoid scanners confirming by accident. Click it in the test.
- HTTP 429. The key used its 2,000 requests for the day; see the limits page.
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.