Playwright Email Testing: Password Reset and Signup
Most E2E suites stop at the email. They stub the mailer, or read the token straight from the database. That skips the bugs that only exist in the message: a link built from the wrong base URL, & left in a query string, a token missing from the plain-text part. With the app's mail going to the sandbox, the test follows the same link a user would click.
Two ways to get the mail there: point the app's SMTP transport at send.smtp.dev with a sandbox account's credentials (settings per framework), or let the app send through its normal provider to an address on a domain whose MX points at the sandbox.
A Mail Helper
Keep the API calls in one file next to the tests, e.g. tests/mail.ts. inboxOf finds an account's INBOX once. findMessage returns the newest message sent to an address, or undefined while it hasn't arrived:
const API = 'https://api.smtp.dev'
const headers = { 'X-API-KEY': process.env.SMTP_DEV_API_KEY! }
async function api(path: string) {
const res = await fetch(API + path, { headers })
if (!res.ok)
throw new Error(`${path} returned ${res.status}`)
return res.json()
}
export async function inboxOf(address: string) {
const { member } = await api(`/accounts?address=${encodeURIComponent(address)}`)
const account = member.find((a: { address: string }) => a.address === address)
const { mailboxes } = await api(`/accounts/${account.id}`)
const inbox = mailboxes.find((m: { path: string }) => m.path === 'INBOX')
return `/accounts/${account.id}/mailboxes/${inbox.id}/messages`
}
export async function findMessage(inbox: string, to: string) {
const { member } = await api(inbox)
const found = member.find((m: { to: { address: string }[] }) => m.to.some(t => t.address === to))
return found && api(`${inbox}/${found.id}`)
}
Password Reset
import { expect, test } from '@playwright/test'
import { findMessage, inboxOf } from './mail'
test('password reset', async ({ page, baseURL }) => {
const address = `reset+${crypto.randomUUID()}@test.example.com`
const inbox = await inboxOf('reset@test.example.com')
await page.goto('/forgot-password')
await page.getByLabel('Email').fill(address)
await page.getByRole('button', { name: 'Send reset link' }).click()
await expect.poll(() => findMessage(inbox, address), { timeout: 30_000 }).toBeTruthy()
const message = await findMessage(inbox, address)
expect(message.subject).toBe('Reset your password')
const link = message.text.match(/https?:\/\/\S*reset\S*/)?.[0]
expect(new URL(link).origin).toBe(new URL(baseURL!).origin)
await page.goto(link)
await page.getByLabel('New password').fill('correct-horse-battery')
await page.getByRole('button', { name: 'Set password' }).click()
await expect(page).toHaveURL(/signin/)
})
expect.poll retries findMessage until the email shows up, backing off to one request a second. If it never arrives, the test fails after 30 seconds on that line.
The origin check catches links built from the wrong base URL, like a production host left in the staging config.
The message's text field is the plain text part. html is an array of HTML parts.
Reading Links from HTML
When the link only exists as a button in the HTML part, render the email in a second page and use the same locators you use on the app:
const mail = await page.context().newPage()
await mail.setContent(message.html.join(''))
const link = await mail.getByRole('link', { name: 'Reset password' }).getAttribute('href')
await mail.close()
That also checks the button text. getAttribute('href') returns the URL as the browser parsed it, so & in the markup comes back as &. A regex over the raw HTML keeps the &, and ?token=abc&email=x reaches the app as token and amp;email.
If the link is in both parts, check both. The text and HTML versions often come from separate templates, and they drift apart.
The test proves the email arrives and its link works. To see how it renders, open the account in a mail client over IMAP.
Signup with a One-Time Code
test('signup sends a code', async ({ page }) => {
const address = `signup+${crypto.randomUUID()}@test.example.com`
const inbox = await inboxOf('signup@test.example.com')
await page.goto('/signup')
await page.getByLabel('Email').fill(address)
await page.getByRole('button', { name: 'Create account' }).click()
await expect.poll(() => findMessage(inbox, address), { timeout: 30_000 }).toBeTruthy()
const { text } = await findMessage(inbox, address)
await page.getByLabel('Code').fill(text.match(/\b\d{6}\b/)?.[0])
await page.getByRole('button', { name: 'Verify' }).click()
await expect(page.getByText('Welcome')).toBeVisible()
})
\b\d{6}\b takes the first six digits in the email, which is fine until the template gains an order number. OTP codes and magic links anchors the pattern, and tests resend, reuse, and links that a mail scanner opens first.
Keeping It Stable
- One address per test.
reset+<uuid>@test.example.comdelivers toreset@test.example.comwith the alias intact into, so parallel workers never read each other's mail. Match on recipient, not arrival order. Plus aliases work on every plan. - Polling stays cheap. A few workers polling once a second sit nowhere near the 4096 requests per minute limit.
- Or skip polling. Subscribe over SSE and resolve when a
Messageevent for the account arrives.
In CI
Start the app with its SMTP settings pointed at the sandbox through webServer in playwright.config.ts. The SMTP_* names are whatever your app reads:
import { defineConfig } from '@playwright/test'
export default defineConfig({
use: { baseURL: 'http://localhost:3000' },
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
env: {
SMTP_HOST: 'send.smtp.dev',
SMTP_PORT: '587',
SMTP_USER: 'app@test.example.com',
SMTP_PASSWORD: process.env.SMTP_PASSWORD!,
},
},
})
Store SMTP_PASSWORD and SMTP_DEV_API_KEY as repository secrets. The CI guide has the GitHub Actions workflow, and Cypress has the same flow for Cypress.
Troubleshooting
| Symptom | Cause |
|---|---|
expect.poll times out | The app didn't send, or sent elsewhere. Check its log for an SMTP error first: send.smtp.dev refuses a recipient whose account doesn't exist |
| The test reads an older email | It took the first message in the list. Match on a recipient only this test uses |
message.text is empty | The template has no plain text part. Read the link from the HTML |
The link contains & | It came from a regex over the raw HTML. Use getAttribute('href') on the rendered message |
| Passes locally, times out in CI | The job is missing SMTP_PASSWORD or SMTP_DEV_API_KEY, or the app under test wasn't started with the sandbox's SMTP settings |
SPF, DKIM, DMARC
Send from staging to a sandbox address and read the SPF, DKIM, and DMARC results on the received message before you change production DNS.
Cypress
Wait for a signup or password reset email in a Cypress test, pull the link or code out of it, and finish the flow. The API key stays in Node.