TestCafe email verification with a real test inbox
TestCafe tests are written in JavaScript or TypeScript and run in Node, while the page under test runs in a browser it controls. That is convenient for email: the test body itself is Node code, so it can call an HTTP API with the built-in fetch without any browser tricks or extra plugins. This guide writes a TestCafe test for an email-verification sign-up. It creates a unique address for each test, waits for the message, reads the code and types it into the page. The code uses CommonJS, which TestCafe accepts, and targets TestCafe 2 and 3 with Node 18 or newer.
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. TestCafe test bodies run in Node, so the wait is a plain asynchronous function call and needs no browser-side request.
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.
Project layout
The project needs two files next to your app's tests: a small helper that talks to the API, and the test itself. A .testcaferc.json file is optional; it can hold the browser and the source folder.
{
"browsers": ["chrome:headless"],
"src": ["tests/"],
"selectorTimeout": 10000,
"assertionTimeout": 10000
}
The helper
Save this as helpers/inbox.js. newInbox gives each test a unique tag and address, waitForEmail waits for the newest matching message and retries on a 408, and deleteEmails removes the messages for a tag. Outside the test body, for example in a hook, the same functions work too.
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 test
Save this as tests/signup.test.js. It uses a TestCafe fixture with a start page, and a test that submits the sign-up form, waits for the email, then enters the code. Replace the selectors and the final assertion with those of your app.
const { Selector } = require("testcafe");
const { newInbox, waitForEmail, deleteEmails } = require("../helpers/inbox");
const APP = process.env.APP_URL || "http://localhost:3000";
fixture("Sign-up").page(APP + "/signup");
test("a new user verifies the email with the emailed code", async (t) => {
const inbox = newInbox("testcafe-signup");
try {
await t
.typeText(Selector("input[name=email]"), inbox.email)
.typeText(Selector("input[name=password]"), "correct horse battery staple")
.click(Selector("button").withText("Create account"));
const mail = await waitForEmail(inbox.tag, { subject: "verify" });
await t.expect(mail.otp).match(/^[0-9]{4,8}$/);
await t
.typeText(Selector("input[name=code]"), mail.otp)
.click(Selector("button").withText("Verify"))
.expect(Selector("h1").withText("Welcome").exists).ok();
} finally {
await deleteEmails(inbox.tag);
}
});
The tag is created inside the test, so two tests never share one, and TestCafe's concurrency option, which runs several browser instances at the same time, cannot make them read each other's messages. Run the suite with npx testcafe chrome:headless tests/, or with npx testcafe alone if you use the configuration file above.
A magic link instead of a code
If your app sends a link, read magic_link from the same message and navigate to it with t.navigateTo:
test("a new user verifies the email with the emailed link", async (t) => {
const inbox = newInbox("testcafe-link");
try {
await t
.typeText(Selector("input[name=email]"), inbox.email)
.click(Selector("button").withText("Email me a link"));
const mail = await waitForEmail(inbox.tag);
await t
.expect(mail.magic_link).contains("/verify")
.navigateTo(mail.magic_link)
.expect(Selector("h1").withText("Welcome").exists).ok();
} finally {
await deleteEmails(inbox.tag);
}
});
Put the helper imports in the same file as the first test. The snippet above shows only the second test, so keep the require lines and the fixture from the first snippet at the top.
Timeouts
TestCafe has its own timeouts for selectors and assertions, but the wait for an email is not a TestCafe command, so those timeouts do not apply to it. The helper waits up to 25 seconds per request and three attempts, about 75 seconds in the worst case. That is fine for tests, which do not have a global time limit by default. If you set --test-execution-timeout or a CI job limit, make sure it exceeds the worst case, otherwise a slow email shows up as a TestCafe timeout instead of the helper's readable error.
Running in CI
- Store
ASSERTINBOX_KEYas a secret andASSERTINBOX_NAMESPACEas an ordinary variable. Never print them. - Use a headless browser:
chrome:headlessorfirefox:headless. - With
-c 3TestCafe runs three browser instances in parallel. The unique tags make this safe. - Delete messages in a
finallyblock as above. They are deleted automatically after 24 hours anyway.
Troubleshooting
- "Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE". The environment variables are not set in the shell that starts TestCafe.
- "No matching email arrived". Check that the app sent mail to the address, and that the
subjectfilter matches part of the real subject. Remove the filter to see whether any message arrives. - The test fails before the wait. The page selectors do not match. Try the selectors with TestCafe's live mode or the browser's developer tools.
- 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: Playwright email verification, Puppeteer email verification and WebdriverIO email OTP. 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.