Test an Express and Nodemailer sign-up verification email with Playwright
A sign-up flow that sends a verification email has three places to break: the route that creates the token, the SMTP transport, and the template that builds the link. This guide tests all three together. It shows a minimal Express app that sends the email with Nodemailer over SMTP, and a Playwright Test (plain JavaScript) that signs up with a unique address, waits for the message, checks the link, opens it and asserts that the account is verified.
Why a real inbox, not a mocked transport
Nodemailer ships a JSON transport and many projects replace the transport with a stub in tests. A stub proves that your code called sendMail; it cannot prove that the message left the process. A real inbox catches mistakes that a mock hides: a wrong SMTP host, port or credentials in the environment, a secure flag that does not match the port, a sender address the provider refuses, a template that renders undefined in the link, and a base URL that still points at localhost. Those are the failures users see. Keep your fast unit tests with the stub, and add this one end-to-end test for the path that matters.
The app under test
Save this as server.js. It keeps users in memory to stay short; replace that with your database. The SMTP settings come from environment variables, and BASE_URL is the public address that goes into the link. Install the dependencies with npm install express nodemailer.
const crypto = require("crypto");
const express = require("express");
const nodemailer = require("nodemailer");
const app = express();
app.use(express.json());
const BASE_URL = process.env.BASE_URL || "http://localhost:3000";
const users = new Map();
const transport = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT || 587),
secure: process.env.SMTP_SECURE === "true",
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});
app.post("/signup", async (req, res) => {
const email = String(req.body.email || "").toLowerCase();
if (!email.includes("@")) return res.status(400).json({ error: "invalid_email" });
const token = crypto.randomBytes(16).toString("hex");
users.set(email, { token, verified: false });
const link = BASE_URL + "/verify?token=" + token;
try {
await transport.sendMail({
from: process.env.MAIL_FROM,
to: email,
subject: "Verify your email address",
text: "Welcome. Confirm your address by opening " + link,
html: '<p>Welcome. <a href="' + link + '">Confirm your address</a>.</p>',
});
} catch (err) {
return res.status(502).json({ error: "mail_failed", message: err.message });
}
res.status(202).json({ ok: true });
});
app.get("/verify", (req, res) => {
for (const user of users.values()) {
if (user.token === req.query.token) {
user.verified = true;
return res.send("<h1>Email verified</h1>");
}
}
res.status(400).send("<h1>Invalid link</h1>");
});
app.get("/users/:email", (req, res) => {
const user = users.get(req.params.email.toLowerCase());
if (!user) return res.status(404).json({ error: "not_found" });
res.json({ verified: user.verified });
});
app.listen(Number(process.env.PORT || 3000));
The /users/:email route exists only so the test can assert the stored state; in a real app you would assert through the UI or your own API. Send mail through a transactional service you control, and give it the address the test enters. The address is an AssertInbox address, so the provider delivers to assertinbox.com like any other domain.
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, links and magic_link. Messages are deleted after 24 hours. Each test uses its own tag, so parallel tests never read each other's mail.
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.
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 deleteEmails(tag) {
await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { method: "DELETE", headers: headers() });
}
module.exports = { newInbox, waitForEmail, deleteEmails };
The test
Save this as tests/signup.spec.js. Set APP_URL to the address the running app listens on, and start the app with real SMTP settings and a matching BASE_URL. The test posts to the sign-up route, waits for the email by subject, checks the link and the message, and opens the link in the browser.
const { test, expect } = require("@playwright/test");
const { newInbox, waitForEmail, deleteEmails } = require("./inbox");
const APP = process.env.APP_URL || "http://localhost:3000";
test.describe("Express sign-up verification", () => {
test.setTimeout(120000);
let inbox;
test.beforeEach(() => {
inbox = newInbox("express");
});
test.afterEach(async () => {
await deleteEmails(inbox.tag);
});
test("the verification email arrives and the link verifies the account", async ({ page, request }) => {
const res = await request.post(APP + "/signup", { data: { email: inbox.email } });
expect(res.status()).toBe(202);
const mail = await waitForEmail(inbox.tag, { subject: "verify" });
expect(mail.magic_link).toBeTruthy();
expect(new URL(mail.magic_link).host).toBe(new URL(APP).host);
let state = await (await request.get(APP + "/users/" + encodeURIComponent(inbox.email))).json();
expect(state.verified).toBe(false);
await page.goto(mail.magic_link);
await expect(page.getByRole("heading", { name: "Email verified" })).toBeVisible();
state = await (await request.get(APP + "/users/" + encodeURIComponent(inbox.email))).json();
expect(state.verified).toBe(true);
});
test("a failing SMTP server is reported by the app, not swallowed", async ({ request }) => {
const res = await request.post(APP + "/signup", { data: { email: "not-an-address" } });
expect(res.status()).toBe(400);
});
});
Run it with APP_URL=http://localhost:3000 npx playwright test tests/signup.spec.js. The host assertion catches a BASE_URL that was left at its default, and the unverified check before the click proves that opening the link, not the sign-up request, changes the state.
Mistakes this test finds
- The wait times out. Look at the app's response first:
502 mail_failedcarries the SMTP error text. A provider may also accept the message and drop it later; check its delivery log. - The link points at localhost.
BASE_URLis unset in the environment that sends the mail. The host assertion fails with the value it found. - The link is missing from the message. The HTML part renders without the token. Print
mail.linksto see what AssertInbox extracted. - TLS errors. Port 465 normally needs
secure: true; ports 587 and 25 use STARTTLS withsecure: false. - HTTP 429. 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 and API-only tests in Node.js. 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.