AssertInbox

WebdriverIO email OTP tests

WebdriverIO tests that sign up a user need the one-time code from the verification email. This guide adds a custom command, browser.waitForEmail(tag), to a WebdriverIO project that uses the Mocha framework, in plain JavaScript. The test fills the sign-up form with a unique address, waits for the email through one HTTP call, and types the code into the next step. A second test follows the magic link instead.

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, with otp, magic_link and links already extracted. Messages are deleted after 24 hours.

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 CI secrets.

curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}

Export both values for the tests: ASSERTINBOX_KEY is the api_key and ASSERTINBOX_NAMESPACE is 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 listed in the limits page.

The custom command

WebdriverIO lets you register your own commands with browser.addCommand. Put this in test/support/inbox.js. It needs Node 18 or newer for the built-in fetch. Because the command talks to AssertInbox from the Node process that runs the tests, nothing about the key reaches the browser.

const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;

function newInbox(prefix) {
  const random = Math.random().toString(36).slice(2, 8);
  const tag = (prefix + "-" + Date.now() + "-" + random).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);
  }
  throw new Error("No email arrived for tag " + tag);
}

async function deleteEmails(tag) {
  await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), {
    method: "DELETE",
    headers: { Authorization: "Bearer " + KEY },
  });
}

function registerInboxCommands(browser) {
  browser.addCommand("waitForEmail", (tag, filters) => waitForEmail(tag, filters));
  browser.addCommand("clearEmails", (tag) => deleteEmails(tag));
}

module.exports = { newInbox, registerInboxCommands };

Register the commands once, in the before hook of wdio.conf.js:

const { registerInboxCommands } = require("./test/support/inbox");

exports.config = {
  runner: "local",
  specs: ["./test/specs/**/*.js"],
  maxInstances: 4,
  capabilities: [{ browserName: "chrome", "goog:chromeOptions": { args: ["--headless=new"] } }],
  framework: "mocha",
  reporters: ["spec"],
  baseUrl: process.env.APP_URL || "http://localhost:3000",
  mochaOpts: { ui: "bdd", timeout: 120000 },
  before: function (capabilities, specs, browser) {
    registerInboxCommands(browser);
  },
};

The tests

Save this as test/specs/signup.js. Replace the selectors and the success text with those of your app. Each test builds its own address, so tests running in parallel never read the same inbox.

const assert = require("node:assert");
const { newInbox } = require("../support/inbox");

describe("sign-up email verification", () => {
  let inbox;

  beforeEach(async () => {
    inbox = newInbox("wdio");
    await browser.url("/signup");
    await $("input[name=email]").setValue(inbox.email);
    await $("button[type=submit]").click();
  });

  afterEach(async () => {
    await browser.clearEmails(inbox.tag);
  });

  it("verifies with the one-time code", async () => {
    const mail = await browser.waitForEmail(inbox.tag);
    assert.match(mail.otp || "", /^[0-9]{4,8}$/, "subject was " + mail.subject);

    const code = await $("input[name=code]");
    await code.waitForDisplayed({ timeout: 15000 });
    await code.setValue(mail.otp);
    await $("button[type=submit]").click();

    await expect($("body")).toHaveText(expect.stringContaining("Email verified"));
  });

  it("verifies with the magic link", async () => {
    const mail = await browser.waitForEmail(inbox.tag);
    assert.ok(mail.magic_link, "no verification link in the email");

    await browser.url(mail.magic_link);
    await expect($("body")).toHaveText(expect.stringContaining("Email verified"));
  });
});

Run it with npx wdio run wdio.conf.js. maxInstances: 4 lets four spec files run at once; the unique tags keep them apart.

Waiting for the page and for the email

WebdriverIO's own waits, such as waitForDisplayed, poll the page until an element appears. The email wait is a different kind of wait: it is one request that the server holds open until a matching message arrives, so it returns as soon as the email does and uses no polling in your test code. Keep the two apart. Wait for the email first, then wait for the field you need to type into.

When the app sends a second email

A "resend code" button sends another message to the same address, and /v1/wait returns the newest one for the tag, which might still be the first. Pass the id of the message you already read as after:

it("sends a new code on resend", async () => {
  const first = await browser.waitForEmail(inbox.tag);
  await $("#resend").click();
  const second = await browser.waitForEmail(inbox.tag, { after: first.id });
  assert.notStrictEqual(second.id, first.id);
});

The same parameter works with from and subject filters when your app sends several kinds of email to one address.

Troubleshooting

Related guides: Playwright email verification, Cypress OTP login, sign-up email tests in Node.