Cucumber.js email verification tests with Playwright
Cucumber.js lets a team describe behaviour in Gherkin, the plain-language Given, When, Then format, and then runs it through JavaScript step definitions. Email verification is a good fit because the scenario reads the way a user thinks: sign up, get a code by email, type it in. This guide builds that scenario with @cucumber/cucumber, a Playwright browser that is started and stopped in hooks, and a unique AssertInbox address for each scenario. The code uses CommonJS and targets Cucumber.js 9 and newer 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. Cucumber creates a new world object for every scenario, so the inbox created in a Before hook is private to that scenario.
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
features/
signup.feature
steps/
signup.steps.js
support/
hooks.js
inbox.js
Cucumber.js loads support files from features by default, so no configuration is needed beyond installing the packages: npm install --save-dev @cucumber/cucumber playwright, followed by npx playwright install chromium to get the browser. Run the scenarios with npx cucumber-js.
The feature file
Save this as features/signup.feature. It contains one scenario with the code and one for a magic link; change the wording to match your product.
Feature: Email verification at sign-up
Scenario: A new user verifies the address with the emailed code
Given a visitor with a fresh test inbox
When they sign up with that address
And they enter the code from the verification email
Then they see the welcome page
Scenario Outline: A new user can verify with the emailed link
Given a visitor with a fresh test inbox
When they sign up with that address
And they open the link in the verification email
Then they see the welcome page
Examples:
| note |
| link in the email |
The helper
Save this as features/support/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 };
Hooks
Save this as features/support/hooks.js. BeforeAll starts one browser for the run and Before gives each scenario its own browser context, so cookies never leak between scenarios. After closes the context and deletes the scenario's messages. The default Cucumber step timeout is 5 seconds, which is too short for an email wait that can take up to 25 seconds per attempt, so the file raises it.
const { Before, After, BeforeAll, AfterAll, setDefaultTimeout } = require("@cucumber/cucumber");
const { chromium } = require("playwright");
const { newInbox, deleteEmails } = require("./inbox");
setDefaultTimeout(90 * 1000);
let browser;
BeforeAll(async function () {
browser = await chromium.launch();
});
AfterAll(async function () {
await browser.close();
});
Before(async function () {
this.app = process.env.APP_URL || "http://localhost:3000";
this.inbox = newInbox("cucumber");
this.context = await browser.newContext();
this.page = await this.context.newPage();
});
After(async function () {
await this.context.close();
await deleteEmails(this.inbox.tag);
});
Step definitions
Save this as features/steps/signup.steps.js. Use ordinary function expressions, not arrow functions, so that this is the scenario's world. Replace the locators and texts with those of your app.
const assert = require("node:assert");
const { Given, When, Then } = require("@cucumber/cucumber");
const { waitForEmail } = require("../support/inbox");
Given("a visitor with a fresh test inbox", function () {
assert.ok(this.inbox.email.endsWith("@assertinbox.com"));
});
When("they sign up with that address", async function () {
await this.page.goto(this.app + "/signup");
await this.page.getByLabel("Email").fill(this.inbox.email);
await this.page.getByLabel("Password").fill("correct horse battery staple");
await this.page.getByRole("button", { name: "Create account" }).click();
});
When("they enter the code from the verification email", async function () {
const mail = await waitForEmail(this.inbox.tag, { subject: "verify" });
assert.match(mail.otp, /^[0-9]{4,8}$/);
await this.page.getByLabel("Code").fill(mail.otp);
await this.page.getByRole("button", { name: "Verify" }).click();
});
When("they open the link in the verification email", async function () {
const mail = await waitForEmail(this.inbox.tag, { subject: "verify" });
assert.ok(mail.magic_link, "the email has no verification link");
await this.page.goto(mail.magic_link);
});
Then("they see the welcome page", async function () {
await this.page.getByRole("heading", { name: "Welcome" }).waitFor({ timeout: 10000 });
});
The Scenario Outline above has a single example row, which is enough to show the syntax. Add rows when your steps take parameters, for example different subjects or languages, and use <note>-style placeholders in step text.
Why a context per scenario
Starting a browser is slow, but creating a browser context inside a running browser is fast and gives you clean storage. Sharing the browser and isolating the context is the usual compromise: scenarios stay independent and the run stays quick. If you use Cucumber's --parallel option, each worker process runs its own BeforeAll, so each has its own browser, and the unique tags still keep the inboxes apart.
Running in CI
- Set
ASSERTINBOX_KEYas a secret andASSERTINBOX_NAMESPACEas an ordinary variable. Never print them. - Install the Playwright browser in the job, or use an image that already contains it.
- Write a report with
--format html:report.htmland keep it as a job artifact. It contains the scenario names and failures, but not the key, as long as your steps never print it.
Troubleshooting
- "function timed out, ensure the promise resolves within 5000 milliseconds". The default timeout is still in force. Check that
setDefaultTimeoutis called in a support file that Cucumber loads. - "Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE". The variables are not set in the shell that runs Cucumber.
- Undefined step. A sentence in the feature file has no matching definition. Cucumber prints a snippet you can paste.
thisis undefined in a step. You used an arrow function. Usefunction () {}.- 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: Behave, Playwright email verification and Puppeteer email verification. 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.