Test team invitation emails with Playwright
Team invitations involve two people and one email. An admin enters an address, the app sends a link, and the invitee opens it in a browser that has never seen the app, sets a password and lands in the team. Testing this by hand means a second mailbox and a second browser profile. In Playwright you can use two browser contexts, which are isolated like two profiles, and a unique AssertInbox address as the invitee. This guide covers the happy path and the two failures that matter most: an invite that was revoked and an invite that has expired.
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. The invitee's address is a fresh tag for each test, so an invitation sent by an earlier run can never satisfy this run.
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.
Why two browser contexts
A Playwright context has its own cookies and storage. The admin's session lives in one context and the invitee opens the link in another. If you reused one context, the invitee link would open while the admin is still signed in, and you would not notice an app that mishandles that case, or that logs the invitee in as the admin. Two contexts in one test keep the roles apart and the test fast, because they share a single browser process.
The helper
Save this as tests/inbox.js. It needs Node 18 or newer for the built-in fetch.
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 happy path
Save this as tests/invite.spec.js. The admin account is created by a set-up call that you provide; signInAsAdmin below is a placeholder for it. Labels, button names and subjects need to match 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 signInAsAdmin(page) {
await page.goto(APP + "/login");
await page.getByLabel("Email").fill(process.env.ADMIN_EMAIL);
await page.getByLabel("Password").fill(process.env.ADMIN_PASSWORD);
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
}
async function invite(page, email) {
await page.goto(APP + "/team");
await page.getByLabel("Email address").fill(email);
await page.getByRole("button", { name: "Send invite" }).click();
await expect(page.getByText(email)).toBeVisible();
}
test("an invited person can join the team", async ({ browser }) => {
const invitee = newInbox("invite");
const adminContext = await browser.newContext();
const inviteeContext = await browser.newContext();
try {
const admin = await adminContext.newPage();
await signInAsAdmin(admin);
await invite(admin, invitee.email);
const mail = await waitForEmail(invitee.tag, { subject: "invited" });
expect(mail.magic_link).toContain("/accept-invite");
const guest = await inviteeContext.newPage();
await guest.goto(mail.magic_link);
await guest.getByLabel("Password").fill("correct horse battery staple");
await guest.getByRole("button", { name: "Join team" }).click();
await expect(guest.getByRole("heading", { name: "Dashboard" })).toBeVisible();
await admin.reload();
await expect(admin.getByText(invitee.email)).toBeVisible();
await expect(admin.getByText("Pending")).toHaveCount(0);
} finally {
await deleteEmails(invitee.tag);
await adminContext.close();
await inviteeContext.close();
}
});
The last two assertions go back to the admin's page and check the other side of the flow: the invitee now appears as a member and is no longer listed as pending. That is where many bugs hide, since the invitee's screen can look right while the team list is stale.
A revoked invite
When an admin cancels an invitation, the link in the already-sent email must stop working. Send the invite, wait for the email, revoke the invite as the admin, and only then open the link as the invitee.
test("a revoked invitation cannot be accepted", async ({ browser }) => {
const invitee = newInbox("revoked");
const adminContext = await browser.newContext();
const inviteeContext = await browser.newContext();
try {
const admin = await adminContext.newPage();
await signInAsAdmin(admin);
await invite(admin, invitee.email);
const mail = await waitForEmail(invitee.tag, { subject: "invited" });
await admin.getByRole("row", { name: invitee.email }).getByRole("button", { name: "Revoke" }).click();
await expect(admin.getByText(invitee.email)).toHaveCount(0);
const guest = await inviteeContext.newPage();
await guest.goto(mail.magic_link);
await expect(guest.getByText(/revoked|no longer valid|expired/i)).toBeVisible();
await expect(guest.getByLabel("Password")).toHaveCount(0);
} finally {
await deleteEmails(invitee.tag);
await adminContext.close();
await inviteeContext.close();
}
});
An expired invite
Real invitations may last days, and a test cannot wait that long. There are two honest ways to test expiry. The first is a test-only hook in your app that sends an invite with a short lifetime, for example an environment variable that sets the lifetime to a few seconds in the test environment. The test then sends the invite, waits for the email, sleeps past the lifetime and opens the link. The second is to create the expired invite directly in your test database or through a test-only endpoint, and then call GET /v1/wait for the email as before. Either way, assert the same thing as for revocation: a clear message and no password form. Do not change your production code only to make the test pass; keep the short lifetime behind a setting that is off in production.
test("an expired invitation shows a clear message", async ({ browser, request }) => {
const invitee = newInbox("expired");
const context = await browser.newContext();
try {
const res = await request.post(APP + "/api/test/invitations", {
data: { email: invitee.email, expiresInSeconds: 2 },
headers: { "x-test-token": process.env.TEST_HOOK_TOKEN },
});
expect(res.ok()).toBeTruthy();
const mail = await waitForEmail(invitee.tag, { subject: "invited" });
await new Promise((resolve) => setTimeout(resolve, 3000));
const guest = await context.newPage();
await guest.goto(mail.magic_link);
await expect(guest.getByText(/expired/i)).toBeVisible();
} finally {
await deleteEmails(invitee.tag);
await context.close();
}
});
More cases worth a test
- Inviting an existing member. The app should refuse, or send a different message. Assert on whichever it does.
- Re-sending an invite. After a resend, wait for the newest mail and assert that the old link is rejected if your app replaces the token.
- Roles. Invite as viewer and assert that the new member cannot reach the admin pages.
- Invites for several addresses at once. Use one tag per invitee, so each wait returns exactly its own mail.
Troubleshooting
- The wait times out. Look at the app's outbound mail log: some apps queue invitations and send them from a worker that is not running in the test environment.
- The invitee is signed in as the admin. You reused a context. Use a second one, as above.
- The link goes to production. Set the app's public base URL for the test environment, or rewrite the host in the test before opening the link.
- HTTP 429. The daily allowance is 2,000 requests per key.
Retry-Aftergives the seconds until 00:00 UTC.
Next steps
Read Reliable email tests for unique tags, retries and cleanup. Related guides: the email-change confirmation flow, Playwright email verification and password reset emails. 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.