AssertInbox

Jest email verification test

Jest is the most common test runner for Node projects, and its default configuration loads test files as CommonJS. This guide writes an API-level sign-up test in Jest: the test calls your sign-up endpoint, reads the verification email through AssertInbox with the CommonJS client file, and asserts on the code and the link. No browser is involved, so the tests are fast. It targets Jest 29 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, so each test builds its own tag and never reads another test's mail, even when Jest runs test files in parallel workers.

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

Jest runs CommonJS unless you opt in to ES modules, so use the CommonJS copy of the client. It is one file with no dependencies. Put it next to your tests and install Jest:

npm install --save-dev jest
curl -o test/assertinbox.cjs https://assertinbox.com/sdk/assertinbox.cjs

The file exports AssertInbox, whose methods used here are uniqueTag(), address(tag), wait(), waitForOtp(), waitForLink() and delete(tag). If your project uses ES modules and runs Jest with --experimental-vm-modules, use assertinbox.mjs instead; the client page describes both files.

Try it first against the practice app

The practice app exists so you can 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 use the sign-up and verify paths /signup and /verify, and the test below runs unchanged against it. Against your own app, change the paths and the request body.

The test file

Save this as test/signup-email.test.js and run it with npx jest. The helper creates one client for the file and one tag for each test, and the afterEach hook deletes that tag's messages, even when the test failed.

const { AssertInbox } = require("./assertinbox.cjs");

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

let tag;
let email;

beforeEach(() => {
  tag = inbox.uniqueTag("jest");
  email = inbox.address(tag);
});

afterEach(async () => {
  await inbox.delete(tag).catch(() => {});
});

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(() => ({})) };
}

test("sign-up emails a code that verifies the address", async () => {
  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);
}, 90000);

test("the confirmation link points at our host over https", async () => {
  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:");
}, 90000);

test("a wrong code is rejected", async () => {
  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);
}, 90000);

Timeouts

Jest fails any test that takes longer than five seconds by default, and a real email can take longer than that. Each wait call here may take up to 20 seconds and is retried twice on 408, so the tests ask for 90 seconds. There are three ways to set it. The third argument of test sets one test, as above. jest.setTimeout(90000) at the top of a file sets every test in that file. testTimeout: 90000 in jest.config.js sets it for the whole project. A wait that succeeds returns as soon as the email arrives, so a high limit does not make a healthy run slower; it only decides how long a broken run takes to fail.

Two emails from one action

When one action sends two emails, such as a welcome email and a verification email, 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. The practice app's resend endpoint is a good place to try it.

Parallel workers

Jest runs test files in separate worker processes and tests inside a file one after another. Because every test builds its own tag from the clock and a random part, two workers never share an inbox, and you do not need --runInBand. Do not build the tag at the top level of a file and reuse it across tests: a second test would then read the first test's email.

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 jest. Never print the key. The key allows 2,000 requests a day; each test uses a handful.

Troubleshooting

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

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.