AssertInbox

Vitest email verification test

Vitest is a fast test runner that loads test files as ES modules, which suits the ESM client file from AssertInbox. This guide writes an API-level sign-up test: the test calls your sign-up endpoint, reads the verification email through AssertInbox, and asserts on the code and the link. It uses test.concurrent so several email tests run at once, each with its own tag. It targets Vitest 1 or newer 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 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: a test that builds its own tag never reads another test's mail, which is what makes concurrent tests safe.

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 keep 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.

Install the client

Vitest understands ES modules, so use assertinbox.mjs. It is one file with no dependencies:

npm install --save-dev vitest
curl -o test/assertinbox.mjs https://assertinbox.com/sdk/assertinbox.mjs

Its methods used here are uniqueTag(), address(tag), wait(), waitForOtp(), waitForLink() and delete(tag). See the client page for all of them.

Configuration

Vitest fails a test after five seconds by default. Waiting for an email can take longer, so raise the limit for the project in vitest.config.mjs:

import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    testTimeout: 90000,
    hookTimeout: 30000,
  },
});

A wait that succeeds returns as soon as the email arrives, so a high limit does not slow down a healthy run. It only decides how long a broken run takes to fail. You can also pass a timeout as the last argument of one test, test("...", async () => {}, 90000).

Try it first against the practice app

The practice app lets you see a green test before you touch your own application. POST https://assertinbox.com/practice/api/signup with {"email": "<address>"} returns 201 and emails a six-digit code and a confirmation link to that address and nowhere else. POST /practice/api/verify with the email and the code returns {"verified": true}. Set APP_URL=https://assertinbox.com/practice/api and the test below runs unchanged. Against your own app, change the paths and the request body.

The test file

Save this as test/signup-email.test.mjs and run it with npx vitest run. Each test creates its own tag inside the test body and removes its messages in a finally block. The tag is created inside the test, not in a shared beforeEach, because concurrent tests in one file would overwrite a shared variable.

import { expect, test } from "vitest";
import { AssertInbox } from "./assertinbox.mjs";

const APP = process.env.APP_URL ?? "http://localhost:3000/api";
const inbox = new AssertInbox({
  key: process.env.ASSERTINBOX_KEY,
  namespace: process.env.ASSERTINBOX_NAMESPACE,
});

async function post(path, body) {
  const res = await fetch(APP + path, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  return { status: res.status, body: await res.json().catch(() => ({})) };
}

async function withInbox(fn) {
  const tag = inbox.uniqueTag("vitest");
  try {
    await fn({ tag, email: inbox.address(tag) });
  } finally {
    await inbox.delete(tag).catch(() => {});
  }
}

test.concurrent("sign-up emails a code that verifies the address", () =>
  withInbox(async ({ tag, email }) => {
    const signup = await post("/signup", { email, password: "correct-Horse-battery-1" });
    expect(signup.status).toBeLessThan(300);

    const code = await inbox.waitForOtp(tag, { retries: 2 });
    expect(code).toMatch(/^[0-9]{6}$/);

    const verify = await post("/verify", { email, code });
    expect(verify.status).toBe(200);
    expect(verify.body.verified).toBe(true);
  }),
);

test.concurrent("the confirmation link points at our host over https", () =>
  withInbox(async ({ tag, email }) => {
    await post("/signup", { email, password: "correct-Horse-battery-1" });

    const link = new URL(await inbox.waitForLink(tag, { retries: 2 }));
    expect(link.host).toBe(new URL(APP).host);
    expect(link.protocol).toBe("https:");
  }),
);

test.concurrent("a wrong code is rejected", () =>
  withInbox(async ({ tag, email }) => {
    await post("/signup", { email, password: "correct-Horse-battery-1" });
    const mail = await inbox.wait({ tag, retries: 2 });

    const wrong = mail.otp === "000000" ? "111111" : "000000";
    const verify = await post("/verify", { email, code: wrong });
    expect(verify.status).toBeGreaterThanOrEqual(400);
  }),
);

Why one tag per test matters here

test.concurrent starts the tests of a file together instead of one after another. Three tests that each wait up to a minute then take about as long as the slowest one. That only works if the tests cannot see each other's mail, and the per-test tag guarantees it. Do not build the tag at the top level of the file and reuse it: the first email to arrive would satisfy all three waits. Separate test files already run in separate workers, so they are isolated in the same way.

Two emails from one action

When one action sends two emails, wait for the first, then pass its id as after to wait for the second: const second = await inbox.wait({ tag, after: first.id }). This stops the second wait from returning the first message again.

Run it in CI

Store ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE as secrets in your CI provider and pass them as environment variables to the step that runs npx vitest run. Use run in CI, because plain vitest starts watch mode. Never print the key. The key allows 2,000 requests a day; each test uses a handful.

Troubleshooting

Related guides: Jest email verification test, sign-up emails without a browser in Node.

Next steps

For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.