AssertInbox

Selenium WebDriver for JavaScript: email verification tests

The selenium-webdriver package drives a real browser from Node.js. It does not know about email, and it should not: your test can call an HTTP API between two browser steps. This guide shows a complete sign-up test that creates a unique address, submits the form in a browser, waits for the verification email, reads the code and enters it. It uses the node:test runner that ships with Node, so the only dependency is selenium-webdriver. A Mocha version is shown after that for projects that already use it. The code targets selenium-webdriver 4 and 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. Selenium commands return promises, so the wait is just another awaited call in the test.

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.

Set-up

Install the driver library as a development dependency. Selenium Manager, which is bundled with recent versions of selenium-webdriver, normally finds or downloads the matching browser driver for you; see the Selenium documentation if your CI image blocks downloads.

npm install --save-dev selenium-webdriver
export ASSERTINBOX_KEY=ai_...
export ASSERTINBOX_NAMESPACE=k3x9a1bz
export APP_URL=http://localhost:3000
node --test tests/

The helper

Save this as tests/inbox.js. It builds a unique tag and address, waits for a message with optional subject and after filters and retries when the wait returns 408.

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 with node:test

Save this as tests/signup.test.js. A new browser is started for each test and always closed in after. The wait for the email uses the subject filter, so unrelated mail to the same address is ignored. Replace the locators, button text and the final assertion with those of your app.

const { test, before, after } = require("node:test");
const assert = require("node:assert");
const { Builder, By, until } = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome");
const { newInbox, waitForEmail, deleteEmails } = require("./inbox");

const APP = process.env.APP_URL || "http://localhost:3000";

let driver;

before(async () => {
  const options = new chrome.Options().addArguments("--headless=new");
  driver = await new Builder().forBrowser("chrome").setChromeOptions(options).build();
});

after(async () => {
  if (driver) await driver.quit();
});

test("a new user verifies the email with the emailed code", async () => {
  const inbox = newInbox("selenium-signup");
  try {
    await driver.get(APP + "/signup");
    await driver.findElement(By.name("email")).sendKeys(inbox.email);
    await driver.findElement(By.name("password")).sendKeys("correct horse battery staple");
    await driver.findElement(By.css("button[type=submit]")).click();

    await driver.wait(until.elementLocated(By.name("code")), 10000);

    const mail = await waitForEmail(inbox.tag, { subject: "verify" });
    assert.match(mail.otp, /^[0-9]{4,8}$/);

    await driver.findElement(By.name("code")).sendKeys(mail.otp);
    await driver.findElement(By.css("button[type=submit]")).click();

    const heading = await driver.wait(until.elementLocated(By.css("h1")), 10000);
    assert.match(await heading.getText(), /Welcome/);
  } finally {
    await deleteEmails(inbox.tag);
  }
});

The explicit wait for the code field matters. Without it, the test could call the API while the page is still submitting, which is harmless, but a missing code field would then be reported only after the email wait finishes. Failing early on the page gives a clearer message.

The same test with Mocha

If your project already runs Mocha, the body of the test does not change. Only the hooks and the runner differ. Mocha's default timeout is 2 seconds, which is shorter than one email wait, so raise it for these tests, as the first line below does.

const assert = require("node:assert");
const { Builder, By, until } = require("selenium-webdriver");
const { newInbox, waitForEmail, deleteEmails } = require("./inbox");

describe("sign-up email", function () {
  this.timeout(120000);
  let driver;
  let inbox;

  before(async function () {
    driver = await new Builder().forBrowser("chrome").build();
  });

  beforeEach(function () {
    inbox = newInbox("selenium-mocha");
  });

  afterEach(async function () {
    await deleteEmails(inbox.tag);
  });

  after(async function () {
    await driver.quit();
  });

  it("accepts the emailed code", async function () {
    await driver.get((process.env.APP_URL || "http://localhost:3000") + "/signup");
    await driver.findElement(By.name("email")).sendKeys(inbox.email);
    await driver.findElement(By.css("button[type=submit]")).click();
    await driver.wait(until.elementLocated(By.name("code")), 10000);

    const mail = await waitForEmail(inbox.tag, { subject: "verify" });
    await driver.findElement(By.name("code")).sendKeys(mail.otp);
    await driver.findElement(By.css("button[type=submit]")).click();

    const heading = await driver.wait(until.elementLocated(By.css("h1")), 10000);
    assert.match(await heading.getText(), /Welcome/);
  });
});

Waiting for a second email

For a resend, read the first message and then pass its id as the after filter: waitForEmail(inbox.tag, { subject: "verify", after: first.id }). The wait then ignores everything that arrived earlier, so you can be sure that the code you enter comes from the second message.

Running against a remote Selenium Grid

When tests run on a remote grid, the browser is on another machine but the test process, and therefore the email calls, still run where node runs. That means the API key stays on your own machine or CI runner and is never sent to the grid. Use usingServer(url) on the builder to select the grid, and keep the helper unchanged.

Troubleshooting

Next steps

Read Reliable email tests for unique tags, retries and cleanup. Related guides: Selenium with Python, WebdriverIO email OTP 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.